【发布时间】:2017-03-23 20:29:59
【问题描述】:
我试图在我的单元测试用例中模拟一个 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 调用,而是将其转换为 thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"),Timestamp.valueOf("2017- 02-08 11:29:31.3"), )
-
无法复制。你能显示调用
resultSet.getTimestamp("CREATED_ON")的代码部分吗? -
根据您的要求更新@SergheyBishyr。我也能够使用 thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"),Timestamp.valueOf("2017-02-08 11:29:31.3")) 而不是链接来解决这个问题方法。感谢您的回复。
-
我仍然无法重现此问题。您使用的是哪个
Mockito版本? -
我正在使用 mockito-all-1.9.5.jar 和 junit-4.11.jar