java - 模拟结果集 getTimeStamp 不适用于超过 1 行

标签 java junit mockito

我正在尝试在单元测试用例中模拟 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/

相关文章:

java - 以任意顺序对字符串进行排序

java - 示例 wikitude SDK

java - Eclipse 在运行 Spring JUnit 时抛出 java.lang.NullPointerException

java - 检查对象数组上的模拟调用

java - 在java中读取文本文件并将其转换为字符串

java - 根据 Dart 中的天数获取日期

testing - 从测试中重构 JUnit 规则

java - 为什么 Spring TestExecution ExceptionHandler Tests 的 ATestClass 的测试不会失败?

java - java中的导出和导入函数

java - 如何在 Java 中使用 PowerMockito 模拟接口(interface)