问题
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")
}
回答1:
See this post:
Why doesn't Array's == function return true for Array(1,2) == Array(1,2)?
ScalaMock is working fine, but Array equality prevents your expected arg from matching your actual arg.
e.g. this works:
"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")
}
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")
}
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")
}
来源:https://stackoverflow.com/questions/45013138/unable-to-create-stub-with-array-argument-in-scalmock