I'm working on adding JUnit test to an enterprise solution's web services. My question is; how do I - if possible - mock the ERP system in the JUnit tests?
For example I have a getOrders(Connection con, String customerId) method. It, however, makes one call to the ERP system to list all orders like:
public List<Order> getOrders(Connection con, String customerId) {
// Call ERP system
orders = con.fetchOrders(customerId);
// Manipulate result
orders...
return orders;
}
Any way to mock the ERP connection?
I assume you mean mock the Connection object? It's unclear if Connection is an interface or a class. Some mock object libraries only work on interfaces. Here are some of the more popular Java mock object libraries jmock, mockito and easymock
The basic idea would be to create a mock Connection object and have it return data that you want to test.
For example using easymock:
String customerId =...
List<Order> myOrders = ...
Connection mockConnection = EasyMock.createMock(Connection.class);
EasyMock.expect(mockConnection.fetchOrders(customerId)).andReturn(myOrders);
EasyMock.replay(mockConnection);
//call system under test:
List<Orders> results = getOrders(mockConnection, customerId);
List<Orders> expectedResults = ....
assertEquals(expectedResults, results);
If Connection is an interface, then you can simply use something similar to Mockito to verify the messages that are sent to it.
If Connection is a concrete class then it's more difficult. I'd create an interface that duplicated the connection classes public methods and delegated to the appropriate ERP Connection instance.
interface ERPConnection {
List<Order> fetchOrders(String customerID);
}
class MyConnection implements ERPConnection {
private Connection _conn;
public List<Order> fetchOrders(string customerID) {
return _conn.fetchOrders(customerID);
}
}
Now in your code you'll rely on the ERPConnection interface rather than the Connection concrete class. This'll feel like a lot of changes, but it'll insulate you from changes to the ERP system and allow you to mock the interface and test the interaction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With