如何验证 `sender` 在 Mockito 中只发送了 `two ints`?
How to verify that `sender` has only sent `two ints` in Mockito?
Scala 代码:
class Sender {
def send(objects: Any): Unit = ()
}
class User(sender: Sender) {
def hello(): Unit = {
sender.send("hello")
sender.send(1)
sender.send(2)
}
}
我只想测试它发送正确的整数,而不关心字符串:
"user" should {
"send 3 objects, but two ints only" in {
val sender = mock[Sender]
val user = new User(sender)
user.hello()
there was two(sender).send(any[Int]) // !!! failed
there was one(sender).send(1)
there was one(sender).send(2)
}
}
失败并显示消息:
The mock was not called as expected:
sender.send(<any>);
Wanted 2 times:
-> at com.mytest.UserSpec$$anonfun$$anonfun$apply$$anonfun$apply.apply$mcV$sp(UserSpec.scala:50)
But was 3 times. Undesired invocation:
-> at com.mytest.UserSpec$User.hello(UserSpec.scala:63)
java.lang.Exception: The mock was not called as expected:
sender.send(<any>);
Wanted 2 times:
-> at com.mytest.UserSpec$$anonfun$$anonfun$apply$$anonfun$apply.apply$mcV$sp(UserSpec.scala:50)
But was 3 times. Undesired invocation:
-> at com.mytest.UserSpec$User.hello(UserSpec.scala:63)
at com.mytest.UserSpec$$anonfun$$anonfun$apply.apply(UserSpec.scala:50)
at com.mytest.UserSpec$$anonfun$$anonfun$apply.apply(UserSpec.scala:46)
如何写才正确?
您可以使用 haveClass
来获得合适的匹配
there was two(sender).send(haveClass[Integer])
Scala 代码:
class Sender {
def send(objects: Any): Unit = ()
}
class User(sender: Sender) {
def hello(): Unit = {
sender.send("hello")
sender.send(1)
sender.send(2)
}
}
我只想测试它发送正确的整数,而不关心字符串:
"user" should {
"send 3 objects, but two ints only" in {
val sender = mock[Sender]
val user = new User(sender)
user.hello()
there was two(sender).send(any[Int]) // !!! failed
there was one(sender).send(1)
there was one(sender).send(2)
}
}
失败并显示消息:
The mock was not called as expected:
sender.send(<any>);
Wanted 2 times:
-> at com.mytest.UserSpec$$anonfun$$anonfun$apply$$anonfun$apply.apply$mcV$sp(UserSpec.scala:50)
But was 3 times. Undesired invocation:
-> at com.mytest.UserSpec$User.hello(UserSpec.scala:63)
java.lang.Exception: The mock was not called as expected:
sender.send(<any>);
Wanted 2 times:
-> at com.mytest.UserSpec$$anonfun$$anonfun$apply$$anonfun$apply.apply$mcV$sp(UserSpec.scala:50)
But was 3 times. Undesired invocation:
-> at com.mytest.UserSpec$User.hello(UserSpec.scala:63)
at com.mytest.UserSpec$$anonfun$$anonfun$apply.apply(UserSpec.scala:50)
at com.mytest.UserSpec$$anonfun$$anonfun$apply.apply(UserSpec.scala:46)
如何写才正确?
您可以使用 haveClass
来获得合适的匹配
there was two(sender).send(haveClass[Integer])