尝试使用模拟执行简单测试时遇到意外错误。
@RunWith(MockitoJUnitRunner)
class AccessorTest {
@Mock
private DeviceBuilder deviceBuilder
@Test
void shouldCreateDeviceFromFilesystem() {
//given
URI uri = this.class.classLoader.getResource("sample-filesystem").toURI()
File deviceRoot = new File(uri)
Accessor accessor = new Accessor(deviceBuilder)
Device expectedDevice = new Device(deviceRoot)
when(deviceBuilder.build(eq(deviceRoot))).thenReturn(expectedDevice)
//when
Device device = accessor.readFrom(deviceRoot)
//then
assert device == expectedDevice
verify(deviceBuilder).build(deviceRoot)
}
}
DeviceBuilder 是一个单一方法接口(interface) Device::DeviceBuilder#build(File root)。根据 Josh Bloch,设备有一个明确定义的 equals 方法。
在when()行抛出异常,并且作用域中的变量都不为空。完整的异常(exception)是:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded.
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"));
对于它的值(value),这里是我的 POM 的片段:
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.7.0-01</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
</dependencies>
我的怀疑要么是 Groovy 管理类的方式有些奇怪,要么是版本不兼容,但我希望这是我看不到的明显现象。
最佳答案
我知道这是一个老问题,但这可能对其他人有帮助。
问题中描述的问题详细信息位于 http://code.google.com/p/mockito/issues/detail?id=303
我遇到了同样的问题,并通过使用 https://github.com/cyrusinnovation/mockito-groovy-support 提供的库解决了它。
关于exception - 在 Mockito 和 Groovy 2.0.4 中设置期望时出现 InvalidUseOfMatchersException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12961566/