在scala mockito中模拟一个方法的所有重叠版本

Mocking out all overlaoded versions of a method in scala mockito

Mockito-Scala 中,您可以像这样删除方法:

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

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

ScalaAnswer[T] 可以像这样配置 mock 的答案

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")
  }
}