无法在 ScalMock 中使用数组参数创建存根



这是我尝试实现的一个例子。存根总是重新调整为空,但是如果我将Array(1L)更改为*它就可以工作。数组参数似乎有问题。

trait Repo {
def getState(IDs: Array[Long]): String
}

"test" should "pass" in {
val repo = stub[Repo]
(repo.getState _).when(Array(1L)).returns("OK")
val result = repo.getState(Array(1L))
assert(result == "OK")
}

看这篇文章:

为什么数组的 == 函数不返回 true 对于数组 (1,2( == 数组(1,2(?

ScalaMock 工作正常,但数组相等会阻止您预期的参数与实际参数匹配。

例如,这有效:

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

更新 - 混合通配符、文字、参数的示例:

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

最新更新