gpt4 book ai didi

java - 如何在 JUnit 和 Mockito 中模拟 ResultSet 以不返回 null

转载 作者:行者123 更新时间:2023-12-01 19:52:46 25 4
gpt4 key购买 nike

我正在尝试测试 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

如何解决这个问题?您能否发布解决此问题的代码?这对我有很大帮助!

提前致谢!

最佳答案

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

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

关于java - 如何在 JUnit 和 Mockito 中模拟 ResultSet 以不返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50758600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com