2

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

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

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

4

1 回答 1

2

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")
  }
}
于 2019-10-21T16:53:13.660 回答