在 scala mockito 中模拟出方法的所有覆盖版本



在Mockito-Scala中,你可以像这样存根方法:

myMock.doIt(*) returns 1
myMock.doIt(*,*) returns 1
myMock.doIt(*,*)(*) returns 1

有没有办法一次模拟所有重载的方法?

ScalaAnswer[T]可以用来像这样配置模拟的答案

object AnswerAllFoo extends ScalaAnswer[Any] {
def answer(invocation: InvocationOnMock): Any = {
if (invocation.getMethod.getName == "foo") 42 else ReturnsDefaults.answer(invocation)
}
}

然后像这样将其传递给模拟创作

mock[Qux](AnswerAllFoo)

这是一个完整的工作示例

import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.{ReturnsDefaults, ScalaAnswer}
import org.scalatest.{FlatSpec, Matchers}
import org.mockito.{ArgumentMatchersSugar, IdiomaticMockito}
trait Qux {
def foo(s: Seq[Int]): Int
def foo(i: Int, j: String): Int
def bar(s: String): String
}
object AnswerAllFoo extends ScalaAnswer[Any] {
def answer(invocation: InvocationOnMock): Any = {
if (invocation.getMethod.getName == "foo") 42 else ReturnsDefaults.answer(invocation)
}
}
class MockAnyOverload extends FlatSpec with Matchers with IdiomaticMockito with ArgumentMatchersSugar {
"Answer[T]" should "should answer all overloaded methods foo" in {
val qux = mock[Qux](AnswerAllFoo)
qux.foo((Seq(1,0))) shouldBe (42)
qux.foo(1, "zar") shouldBe (42)
qux.bar(*) returns "corge"
qux.bar("") shouldBe ("corge")
}
}

相关内容

  • 没有找到相关文章

最新更新