Reputation: 157
Im trying to test a method in a DAO which uses Calendar. This is the test I have so far:
@Test
public void testGetElectionInfo() throws SQLException {
adminDao.getElectionInfo(1);
verify(mockConn, times(1)).prepareStatement(anyString());
verify(mockPreparedStmnt, times(1)).setInt(anyInt(), anyInt());
verify(mockPreparedStmnt, times(1)).executeQuery();
verify(mockResultSet, times(2)).next();
verify(mockResultSet, times(1)).getString("name");
verify(mockResultSet, times(1)).getTimestamp("startDate");
verify(mockResultSet, times(1)).getTimestamp("endDate");
}
This is the DAO method:
public ElectionInfo getElectionInfo(int electionId) {
ElectionInfo electionInfo = new ElectionInfo();
try {
con = sqlConnection.getConnection();
stmt = con.prepareStatement(NamedQueries.GET_ELECTION_INFO);
stmt.setInt(1, electionId);
rs = stmt.executeQuery();
if(rs.next()) {
String name = rs.getString("name");
Timestamp startDate = rs.getTimestamp("startDate");
Timestamp endDate = rs.getTimestamp("endDate");
Calendar startCalender = Calendar.getInstance();
startCalender.setTime(startDate);
Calendar endCalender = Calendar.getInstance();
endCalender.setTime(endDate);
electionInfo.setName(name);
electionInfo.setStartDate(startCalender);
electionInfo.setEndDate(endCalender);
}
return electionInfo;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, "Couldn't get the election info of the planned elections.", e);
} finally{
closeConnection();
}
return electionInfo;
}
When I run the test, it gives me a
java.lang.NullPointerException
at java.util.Calendar.setTime
How can I resolve this issue? Could you please the post the code that solves this issue? That would help me alot!
Thanks in advance!
Upvotes: 0
Views: 1577
Reputation: 1329
The line,
verify(mockResultSet, times(1)).getTimestamp("startDate");
mocks the call but doesn't ask the mocking library to return a Timestamp value, and so the library returns null causing it to throw a NPE. Try changing to,
verify(mockResultSet, times(1)).getTimestamp("startDate").thenReturn(new Timestamp(0));
and likewise for the other methods too.
Upvotes: 3