gpt4 book ai didi

scala - 无法在ScalMock中使用Array参数创建 stub

转载 作者:行者123 更新时间:2023-12-03 10:07:14 24 4
gpt4 key购买 nike

这是我尝试实现的示例。 stub 始终将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")
}

最佳答案

看到这篇文章:

Why doesn't Array's == function return true for Array(1,2) == Array(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")
}

关于scala - 无法在ScalMock中使用Array参数创建 stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45013138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com