无法创建与ScalMock数组参数存根(Unable to create stub with Arr

2019-10-29 18:22发布

这里是什么,我尽量做到一个例子。 存根总是retuns null,但如果我改变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")
}

Answer 1:

看到这个帖子:

为什么不阵列的==功能阵列(1,2)返回true ==阵列(1,2)?

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


文章来源: Unable to create stub with Array argument in ScalMock