【问题标题】:Mocking resultset getTimeStamp doesn't work for more thans 1 row模拟结果集 getTimeStamp 不适用于超过 1 行
【发布时间】: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

标签: java junit mockito


【解决方案1】:

我可以通过用这个替换上面的代码来解决这个问题

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"));

虽然这解决了我的问题,但我仍然不确定这样做是如何解决的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多