看到这个帖子:
为什么 Array 的 == 函数不为 Array(1,2) == Array(1,2) 返回 true?
ScalaMock 工作正常,但数组相等会阻止您预期的 arg 与您的实际 arg 匹配。
例如这有效:
"test" should "pass" in {
val repo = stub[Repo]
val a = Array(1L)
(repo.getState _).when(a).returns("OK")
val result = repo.getState(a)
assert(result == "OK")
}
但是,还有一种方法可以添加自定义匹配器(在 中定义org.scalamock.matchers.ArgThat
):
"test" should "pass" in {
val repo = stub[Repo]
(repo.getState _).when(argThat[Array[_]] {
case Array(1L) => true
case _ => false
}).returns("OK")
val result = repo.getState(Array(1L))
assert(result == "OK")
}
更新 - 混合通配符、文字、argThat 的示例:
trait Repo {
def getState(foo: String, bar: Int, IDs: Array[Long]): String
}
"test" should "pass" in {
val repo = stub[Repo]
(repo.getState _).when(*, 42, argThat[Array[_]] {
case Array(1L) => true
case _ => false
}).returns("OK")
val result = repo.getState("banana", 42, Array(1L))
assert(result == "OK")
}