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$13$$anonfun$apply$10$$anonfun$apply$1.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$13$$anonfun$apply$10$$anonfun$apply$1.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$13$$anonfun$apply$10.apply(UserSpec.scala:50)
at com.mytest.UserSpec$$anonfun$13$$anonfun$apply$10.apply(UserSpec.scala:46)
如何以正确的方式写出来?
答案 0 :(得分:1)
您可以使用haveClass
来获得正确的匹配
there was two(sender).send(haveClass[Integer])