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

时间:2017-07-10 13:18:47

标签: scala mocking scalatest stubbing scalamock

这是我尝试实现的一个例子。存根总是返回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")
}

1 个答案:

答案 0 :(得分:1)

见这篇文章:

Why doesn't Array's == function return true for Array(1,2) == Array(1,2)?

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

e.g。这有效:

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