scala - Mockito:预期 0 个匹配器,1 个记录
问题描述
我有以下 PlaySpec:
"Service A" must {
"do the following" in {
val mockServiceA = mock[ServiceA]
val mockServiceB = mock[ServiceB]
when(mockServiceA.applyRewrite(any[ClassA])).thenReturn(resultA) // case A
when(mockServiceB.execute(any[ClassA])).thenReturn(Future{resultB})
// test code continuation
}
}
ServiveA
和的定义ServiceB
是
class ServiceA {
def applyRewrite(instance: ClassA):ClassA = ???
}
class ServiceB {
def execute(instance: ClassA, limit: Option[Int] = Some(3)) = ???
}
模拟ServiceA#applyRewrite
工作完美。模拟ServiceB#execute
失败,但有以下异常:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at RandomServiceSpec.$anonfun$new$12(RandomServiceSpec.scala:146)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
尽管异常中包含的说明对我来说似乎有点违反直觉,但我尝试了以下方法:
when(mockServiceB.execute(anyObject[ClassA])).thenReturn(Future{resultB})
when(mockServiceB.execute(anyObject())).thenReturn(Future{resultB})
when(mockServiceB.execute(anyObject)).thenReturn(Future{resultB})
when(mockServiceB.execute(any)).thenReturn(Future{resultB})
when(mockServiceB.execute(any, Some(3))).thenReturn(Future{resultB})
when(mockServiceB.execute(any[ClassA], Some(3))).thenReturn(Future{resultB})
不幸的是,一切都无济于事。唯一改变的是异常所指的预期和记录匹配器的数量。
不过,对我来说最奇怪的是模拟对于案例 A非常有效。
解决方案
使用 mockito-scala 的惯用语法,所有与默认参数相关的东西都将由框架处理
mockServiceB.execute(*) returns Future.sucessful(resultB)
如果你添加猫集成它可以减少到只是
mockServiceB.execute(*) returnsF resultB
更多信息在这里
推荐阅读
- java - Java 添加新对象(H2 数据库)
- mongodb - MongoDB 相当于 Python 的 enumerate()
- .net - dotnet 工具安装 --global dotnet-ef
- firebase - 读取文档中 Firebase Firestore 列表的计数
- amazon-web-services - 如何使用 STSAssumeRoleSessionCredentialsProvider 和 roleSessionName 和 roleArn 为 AWS SDK for Java 2.x 进行配置?
- ios - 如何使一组 UICollectionView 组合布局的高度等于组中最大的 UICollectionViewCell?
- sendgrid - 在 Barracuda Cloud Control 中将 SolarWinds (SendGrid) 电子邮件列入白名单
- android - 使用数据绑定 Android 无法读取字符串标签内的字体标签
- python - 气流传感器 - 超时
- windows - Git windows安装程序不让我选择安装位置