如何将ResultSet模拟为不在JUnit和Mockito中返回null

时间:2018-06-08 10:27:40

标签: java unit-testing junit mockito

我试图在使用Calendar的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

如何解决此问题?你可以在帖子里找到解决这个问题的代码吗?那会对我有所帮助!

提前致谢!

1 个答案:

答案 0 :(得分:3)

这条线, verify(mockResultSet, times(1)).getTimestamp("startDate");模拟调用,但不要求模拟库返回Timestamp值,因此库返回null,导致它抛出NPE。尝试更改为,

verify(mockResultSet, times(1)).getTimestamp("startDate").thenReturn(new Timestamp(0));以及其他方法也是如此。