【问题标题】:Multiple thenReturn not working properly in the Mockito多个 thenReturn 在 Mockito 中无法正常工作
【发布时间】:2015-11-26 09:23:17
【问题描述】:

我正在测试一个调用相同方法 (db.getData()) 两次的方法。但我必须返回两个不同的值。

       Mockito.when(db.someMethod()).thenReturn(valueOne).thenReturn(valueTwo);

然后我尝试了多个thenReturn()

不幸的是,我在第一个和第二个 db.getData() 方法调用中只得到了 valueTwo。

【问题讨论】:

  • 如果你想让它为不同的调用返回两个不同的值,你可以这样做: Mockito.when(db.someMethod()).thenReturn(valueOne); db.someMethod(); Mockito.when(db.someMethod()).thenReturn(valueTwo); db.someMethod();
  • @PiotrPytlik 不正确,请参阅:docs.mockito.googlecode.com/hg/org/mockito/stubbing/…:“您可以为连续的方法调用设置不同的行为。最后的存根(例如:thenReturn("foo"))确定进一步连续调用的行为.".
  • @Adriaan 抱歉,又跑题了。是的,我错了……

标签: java unit-testing mocking mockito


【解决方案1】:

您没有展示很多上下文,但这里有一些想法:

  • 确保 db 确实是一个模拟对象
  • 使用调试器检查 db.someMethod() 是否按预期调用了两次
  • 您也可以使用 thenReturn(valueOne, valueTwo);,尽管这应该没什么区别

我怀疑您的方法被调用了两次以上,并且您错过了第一次调用(返回 valueOne)并且只查看后续调用(都将返回 valueTwo)。

the API:

 //you can set different behavior for consecutive method calls.
 //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
 when(mock.someMethod("some arg"))
  .thenThrow(new RuntimeException())
  .thenReturn("foo");

【讨论】:

  • 我在创建 valueOne 和 valueTwo(实际上是一种复杂的对象)时犯了一些错误。 thenReturn(valueOne, valueTwo) & thenReturn(valueOne).thenReturn(valueTwo) 都正常工作。
【解决方案2】:

可能你在调试,当你想取断点行的数据时,你是从mock中取的,所以它会返回其中一个thenReturn()参数,所以当你恢复测试时,它会测试它使用第二个参数。

如果您怀疑它是否正常工作,我建议您,一次获取所有 thenReturn() 项目,然后您同意它们没问题,再次开始测试,不跟踪 thenReturn() 项目。

【讨论】:

    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多