我正在尝试在单元测试用例中模拟 java.sql.resultset。我使用 mocikto 和 junit 进行断言。所有对 next 和 getString 的调用都被模拟工作正常,但是当我尝试模拟 getTimestamp 时,它仅适用于第一行,即第一个结果集。
when(statement.getResultSet()).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getString("HIST_ID"))
.thenReturn("").thenReturn("").thenReturn("").thenReturn("").thenReturn("");
when(resultSet.getTimestamp("CREATED_ON")).thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:29:31.3"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:29:57.49"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:30:13.47"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:30:33.91"));
我尝试调试它,发现调用 .thenReturn(Timestamp.valueOf("2017-02-08 11:29:31.3")) 给出了这个异常:-
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Timestamp cannot be returned by toString()
此代码适用于一行,但下一行开始给出上述异常。
调用函数有这样的代码-
while (rs != null && rs.next()) {
resp = new ClassA();
resp.setCreatedDt(rs.getTimestamp("CREATED_ON"));
}
任何帮助将不胜感激。
谢谢 陶西夫
最佳答案
我能够通过用此替换上面的代码来解决这个问题
thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"),Timestamp.valueOf("2017-02-08 11:29:31.3"))
而不是链接方法。 完整代码:-
when(statement.getResultSet()).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getString("HIST_ID")).thenReturn("").thenReturn("").thenReturn("").thenReturn("").thenReturn("");
when(resultSet.getTimestamp("CREATED_ON")).thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"),Timestamp.valueOf("2017-02-08 11:29:31.3"), Timestamp.valueOf("2017-02-08 11:29:57.49"), Timestamp.valueOf("2017-02-08 11:30:13.47"), Timestamp.valueOf("2017-02-08 11:30:33.91"));
虽然这解决了我的问题,但我仍然不确定这是如何通过这样做解决的。
关于java - 模拟结果集 getTimeStamp 不适用于超过 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42969125/