Reputation: 806
I am looking for a way to test my Dao classes.
One of my classes gets a datasource like this:
public class OrderEJB implements OrderEjbLocal{
@Resource(mappedName = "java:jboss/datasources/MyDS")
private DataSource dataSource;
@Inject
@DataAccessObject
private UserDAO userDAO;
@Override
public List<Activity> activityList() {
try (Connection connection = dataSource.getConnection();) {
return this.userDAO.findAllActivities(connection);
} catch (SQLException e) {
log.error("error");
throw new RuntimeException(e);
}
}
}
Then I have the class UserDAOImpl with the method
public List<Activity> activityList(Connection con)
How can I test the UserDAOImpl? Do I need something like mockito, jmock, easymock? Also, does the server need to be running when running my Junit test? or is there a way to do it without it?
Thanks
Upvotes: 0
Views: 155
Reputation: 164
You can use Mockito to mock the Connection that you are passing to your UserDAOImpl's activityList method as follows:
UserDAOImpl testInstance = ...; // Not sure how you do this
Connection mockedConnection = mock(Connection.class);
// Business method
testInstance.activityList(mockedConnection);
// Asserts
verify(mockedConnection).prepareStatement("select * from dual"); // Or whatever it is that you need to verify
The server does not need to run at all. When your UserDAOImpl is invoking the methods on the Connection, it is actually executing code that was produced by Mockito and that in turn keeps track of what you have executed to support the verify methods that you write deeper down in the test method(s). It is likely that your UserDAOImpl is also going to do something with the PreparedStatement it gets from Connection#prepareStatement(String) so will also need to mock that. Note that you create mocks that will return mocks automatically:
mock(Connection.class, Mockito.RETURNS_DEEP_STUBS);
Upvotes: 1