I am using Junit
to test my jersey api. I want to test DAO without a database. I tried using Mockito but still not able to use mock object to test the DAO which contains Hibernate calls to DB. I want to write Junit
for my Helper class which calls the DAO.Can anyone provide a solution with some sample code to mock the DB Connections in DAO.
EDIT :
Status.java
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getDBValue() throws SQLException {
DatabaseConnectionDAO dbConnectiondao = new DatabaseConnectionDAO();
String dbValue = dbConnectiondao.dbConnection();
return dbValue;
}
DatabaseConnectionDAO.java
private Connection con;
private Statement stmt;
private ResultSet rs;
private String username;
public String dbConnection() throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
stmt = con.createStatement();
rs =stmt.executeQuery("select * from test");
while(rs.next()){
username = rs.getString(1);
}
}catch(Exception e){
e.printStackTrace();
}finally{
con.close();
}
return username;
}
TestDatabase.java
@Test
public void testMockDB() throws SQLException{
DatabaseConnectionDAO mockdbDAO = mock(DatabaseConnectionDAO.class);
Connection con = mock(Connection.class);
Statement stmt = mock(Statement.class);
ResultSet rs = mock(ResultSet.class);
Client client = Client.create();
WebResource webResource = client.resource("myurl");
ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
verify(mockdbDAO).dbConnection();
//when(rs.next()).thenReturn(true);
when(rs.getString(1)).thenReturn(value);
actualResult = response.getEntity(String.class);
assertEquals(expectedResult,actualResult );
}
I think you may be missing the idea of how the DAO should be mocked. You shouldn't have to worry about any connections. Generally, you just want to mock what happens, when its methods are called, say a
findXxx
method. For instance, say you have this DAO interfaceYou could mock it like
You would then have to "inject" that mocked instance into the class that depends on it. For example, if a resource class needs it, you could inject it via the constructor
No when you hit the
findCustomer
method, the DAO will always return the Customer in the mocked DAO.Here's a complete test, using the Jersey Test Framework
The
Customer
class is simple a POJO with along id
, andString name
. The dependency for The Jersey Test Framework isUPDATE
The above example uses Jersey 1, as I saw that the OP is using Jersey 1. For a complete example using Jersey 2 (with annotation injection), see this post
Short answer just don't !
The code that need to be unit tested is the client of the DAO, hence what need to be mocked are the DAOs. DAOs are the component that will integrate the app with an external system (here a database) so they have to be tested as integration tests (i.e. with a real database).