无法在ScalMock中使用Array参数创建存根 [英] Unable to create stub with Array argument in ScalMock
本文介绍了无法在ScalMock中使用Array参数创建存根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我尝试实现的示例.存根始终将null调整为空,但是如果我将Array(1L)
更改为*
,它将起作用.数组参数似乎有问题.
Here is an example of what I try to achieve. Stub always retuns null, but if I change Array(1L)
to *
it works. It seems there is a problem with array arguments.
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")
}
推荐答案
查看此帖子:
为什么不使用数组==对于Array(1,2)== Array(1,2),函数返回true吗?
ScalaMock工作正常,但是数组相等性会阻止您期望的arg与实际的arg匹配.
ScalaMock is working fine, but Array equality prevents your expected arg from matching your actual 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
中定义)的方法:
However there is also a way to add a custom matcher(defined in 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的示例:
Update - example for mixed wildcards, literals, 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")
}
这篇关于无法在ScalMock中使用Array参数创建存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文