我是 Groovy 的新手(在这方面也是 JMock 的新手),在构建对被模拟方法的参数使用匹配器的期望时遇到了一些麻烦。当我尝试做这样的事情时:
Expectations e = new Expectations();
e.allowing(mockObject).doSomething(Expectations.with(aNonNull(ImmutableCollection.class)))
e.will(returnValue(someResponse))
构建期望时会导致以下错误:
groovy.lang.MissingMethodException: No signature of method: static org.jmock.Expectations.with() is applicable for argument types: (org.hamcrest.core.IsNot) values: [not null]
Possible solutions: with(boolean), with(org.hamcrest.Matcher), with(byte), with(org.hamcrest.Matcher), with(char), with(org.hamcrest.Matcher)
aNonNull 返回 Matcher<T>
(org.hamcrest.core.IsNot 实现 Matcher<T>
)并且有一个 Expectations.with 方法需要一个 Matcher,所以我不确定为什么 Groovy 试图找到一个需要具体类而不是 aNonNull 指定的接口(interface)的 with 版本。我还尝试将 aNonNull 的返回值转换为 Matcher 和 Matcher<T>
错误没有任何变化。我不确定泛型是否有一些东西让 Groovy 感到困惑,或者还有什么需要检查的。
最佳答案
根据JavaDoc,org.jmock.Expectations.with()是一个实例而不是静态方法。这就是您收到错误的原因。
顺便说一句,专门为 Groovy 构建的测试/模拟框架将使您的生活变得更加轻松(即使在测试 Java 代码时)。例如,在 Spock (http://spockframework.org) 中,相同的期望如下所示:
mockObject.doSomething(_ as ImmutableCollection) >> someResponse
另一个需要注意的 Groovy 模拟框架是 GMock (http://code.google.com/p/gmock/)。
关于java - 在 Groovy 中将 Hamcrest 匹配器与 JMock 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4318784/