【问题标题】:How to Mock ResultSet to not return null in JUnit and Mockito如何模拟 ResultSet 在 JUnit 和 Mockito 中不返回 null
【发布时间】: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 行添加两个断言来验证 startDateendDate 不是 null
  • verify(mockResultSet, times(1)).getTimestamp("startDate"); 从这个调用返回一些东西,现在它返回一个 null 导致它抛出一个 NPE
  • @jbx 它出现在 Dao 方法中:startCalender.setTime(startDate);

标签: java unit-testing junit mockito


【解决方案1】:

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

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

【讨论】:

  • 这并没有解决问题(andReturn 没有工作),但是当我看到这篇文章时,我想出了这个:when(mockResultSet.getTimestamp("startDate")).thenReturn(new时间戳(0)); when(mockResultSet.getTimestamp("endDate")).thenReturn(new Timestamp(0));这解决了我的问题!
  • 哎呀!更正了答案中的方法名称。感谢您指出! andReturn 在 EasyMock 中 :)
猜你喜欢
  • 1970-01-01
  • 2021-05-08
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多