0

这是我尝试实现的一个示例。存根总是返回空值,但如果我改变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")
}
4

1 回答 1

2

看到这个帖子:

为什么 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")
 }
于 2017-07-10T19:02:26.197 回答