尝试使用模拟执行简单测试时遇到意外错误。
@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 是单一方法接口 Device::DeviceBuilder#build(File root)。根据 Josh Bloch,Device 具有明确定义的 equals 方法。
在 when() 行上抛出异常,并且范围内的所有变量都不是 null。完整的例外是:
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"));
值得一提的是我的 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 管理类的方式有些奇怪,要么是某些版本不兼容,但我希望这是我看不到的显而易见的事情。