I am testing a Spring JDBC class using the JMockit. The following is the test class:
public class DAOImplTest {
@Tested
DAOImpl daoImpl;
@Mocked
JdbcTemplate mockJdbcTemplate;
@Before
public void setup() throws Exception{
daoImpl = new DAOImpl();
daoImpl.setJdbcTempate(mockJdbcTemplate);
}
@Test
public void testGetSomeString() throws Exception{
final String expectedO = "7c82facc";
final String expectedG = "one";
new Expectations() {{
mockJdbcTemplate.queryForObject(SSODAOImpl.GET_IDS, String.class, expectedO);
result = expectedG;
}};
DAOImpl daoImpl = new DAOImpl();
String actual = daoImpl.getSomeString(expectedO);
assertEquals(expected, actualG);
}
}
The class is throwing NullPointer Exception on line String actual = daoImpl.getSomeString(expectedO)
What's the reason for getting the null pointer exception at the very point?
The following is the DAOImpl class method:
public String getSomeString(String or) {
DAORowMapper rowMapper = new DAORowMapper();
String g = jdbcTemplate.queryForObject(GET_IDS, rowMapper, orgIds);
return g;
}
Here is the stack trace while running the JUnit 4 Test. Again the NullPointer exception is when running the Junit4 Test Case
java.lang.NullPointerException
at com.DAOImpl.getSomeString(DAOImpl.java:31)
at comDAOImplTest.testGetSomeString(DAOImplTest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:597)
Seems like the problem is that within getSomeString()
the jdbcTemplate
field is null
. This is because while you set this field on the daoImpl
field in the setup()
method, you are not using the daoImpl
field....you are shadowing the field with a local variable here:
DAOImpl daoImpl = new DAOImpl();
This local variable doesn't have the jdbcTemplate
field set to the mock object. Remove that line and I'm thinking it will work.