Unable to create stub with Array argument in ScalMock

a 夏天 提交于 2019-12-12 04:49:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!