你能捕获并检查提供给ScalaMock测试方法的参数吗?

时间:2012-09-11 11:43:53

标签: scala mocking scalatest

Java Mocking框架Mockito有一个名为ArgumentCaptor的实用程序类,它会累积一个值列表,因为多次调用验证方法。

ScalaMock是否有类似的机制?

5 个答案:

答案 0 :(得分:2)

有一个引擎盖机制在preview release of ScalaMock3中执行此操作,但它目前没有公开给客户端代码。

你的用例是什么?

您可以使用whereonCall记录here(分别在“谓词匹配”和“返回值”标题下)来实现您的需求。

答案 1 :(得分:2)

Specs2中,您可以使用以下内容:

myMock.myFunction(argument) answers(
    passedArgument => "something with"+passedArgument
)

这将映射到Mockito的ArgumentCaptor。

答案 2 :(得分:0)

使用ArgumentCapture

val subject = new ClassUnderTest(mockCollaborator)
// Create the argumentCapture
val argumentCapture = new ArgumentCapture[ArgumentClazz]

// Call the method under test
subject.methodUnderTest(methodParam)

// Verifications
there was one (mockCollaborator).someMethod(argumentCapture)
val argument = argumentCapture.value
argument.getSomething mustEqual methodParam

答案 3 :(得分:0)

根据the Mockito documentation,您可以直接使用specs2匹配器,例如

val myArgumentMatcher: PartialFunction[ArgumentType, MatchResult[_]] = {
  case argument => argument mustEqual expectedValue
}
there was one(myMock).myFunction(beLike(myArgumentMatcher))

这个解决方案很酷的是,部分功能可以提供非常大的灵活性。你可以对你的论点进行模式匹配等。当然,如果你真的只需要比较参数值,那么就不需要部分函数了,你可以做到

there was one(myMock).myFunction(==_(expectedValue))

答案 4 :(得分:0)

另一种选择是通过扩展现有的匹配器来实现自己的参数捕获器。类似的东西应该成功(对于scalamock 3):

trait TestMatchers extends Matchers {

    case class ArgumentCaptor[T]() {
        var valueCaptured: Option[T] = None
    }

    class MatchAnyWithCaptor[T](captor: ArgumentCaptor[T]) extends MatchAny {
        override def equals(that: Any): Boolean = {
           captor.valueCaptured = Some(that.asInstanceOf[T])
           super.equals(that)
        }
    }

    def capture[T](captor: ArgumentCaptor[T]) = new MatchAnyWithCaptor[T](captor)
}

您可以通过将该特征添加到测试类

来使用此新匹配器
val captor = new ArgumentCaptor[MyClass]

(obj1.method(_: MyClass)).expects(capture(captor)).returns(something)

println(captor.capturedValue)