【发布时间】:2018-06-08 10:27:39
【问题描述】:
我试图在使用日历的 DAO 中测试一个方法。这是我到目前为止的测试:
@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");
}
这是DAO方法:
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;
}
当我运行测试时,它给了我一个
java.lang.NullPointerException
at java.util.Calendar.setTime
我该如何解决这个问题?您能否发布解决此问题的代码?这对我有很大帮助!
提前致谢!
【问题讨论】:
-
是静态方法,需要使用PowerMockito。
-
你能告诉我们这发生在哪一行吗?您能否在第 14 行和第 15 行添加两个断言来验证
startDate和endDate不是null? -
verify(mockResultSet, times(1)).getTimestamp("startDate");从这个调用返回一些东西,现在它返回一个 null 导致它抛出一个 NPE -
@jbx 它出现在 Dao 方法中:startCalender.setTime(startDate);
标签: java unit-testing junit mockito