then return返回in Mockito Mockito运行the code代码.无故[副本]

3npbholx  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(68)

此问题在此处已有答案

Mocking a Spy method with Mockito(4个答案)
18天前关门了。
在Scala中,我注意到在Mockito中使用when和thenReturn时,thenReturn在“替换”函数的返回值之前运行实际的函数。例如─

class clsToTest() {
  def functionToTest: String = {
    if(condition-that-evaluated-to-true-sometimes) {
      throw new RuntimeException("some error")
    }
    "function-completed"
  }
}

testclsToTest() {
   test("test functionToTest") {
     val spiedclsToTest = spy(new clsToTest())
     when(spiedScalaSharedLibConfigManager.functionToTest).thenReturn("value to replace")
     //spiedScalaSharedLibConfigManager.otherFunctionThatUsesFunctionToTest()
  }
}

字符串
但当这条线

when(spiedScalaSharedLibConfigManager.functionToTest).thenReturn("value to replace")


因为有时候condition-that-evaluated-to-true-sometimes的评估结果为True,测试会在没有真实的原因的情况下失败。我正在寻找一种方法来替换返回函数的值,而无需实际运行该函数。我有自己的理由使用间谍而不是嘲笑。

mnemlml8

mnemlml81#

如果你有理由使用spy,那么你需要使用特定的语法来模拟它的方法。
when不适用于间谍。使用doXxx.when(spy).method()

doReturn("value-to-replace")
  .when(spiedScalaSharedLibConfigManager)
  .functionToTest();

字符串
另一种选择是使用mock而不是spy
参考文献:

相关问题