gpt4 book ai didi

scala - Mockito 在 ScalaTest 中的回答

转载 作者:行者123 更新时间:2023-12-04 10:08:42 25 4
gpt4 key购买 nike

有没有 Mockito 的 Answer 的替代品?在 ScalaTest 中?我正在浏览它的documentation ,但没有找到任何东西。

例如,我想对 stub 方法的参数执行一些逻辑。在 Mockito 中,我会做这样的事情:

when(mock.create(any(A.class))).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
A firstArg = (A) invocation.getArguments()[0];
firstArg.callMethod();
return null;
}
});

在 ScalaTest 中,我也可以使用 Mockito。但是,如果有一些对 Scala 更友好的语法来定义这样的 Answer,那就太好了。 .

谢谢你。

最佳答案

我刚刚找到 this blog post .它描述了如何使用隐式转换来实现你想要的。如果您定义这样的隐式转换

implicit def toAnswerWithArgs[T](f: InvocationOnMock => T) = new Answer[T] {
override def answer(i: InvocationOnMock): T = f(i)
}

您可以调用 thenAnswer用一个简单的函数作为参数:
when(mock.someMethodCall()).thenAnswer((i) => calculateReturnValue())

当您的模拟方法没有参数时,还有一个稍短的替代版本。点击链接了解详情。

关于scala - Mockito 在 ScalaTest 中的回答,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15024352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com