【发布时间】:2012-10-18 18:43:36
【问题描述】:
尝试使用模拟执行简单测试时遇到意外错误。
@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,设备具有明确定义的 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 的 sn-p:
<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 管理类的方式有些奇怪,要么是版本不兼容,但我希望这是我看不到的显而易见的事情。
【问题讨论】:
-
我看不出有什么问题。当您执行
when(deviceBuilder.build(deviceRoot)).thenReturn(expectedDevice)时会发生什么? -
我有同样的问题,我不能在 Groovy 上做基本的 hello world 存根
-
对自己的回答晚了,我发现的问题是因为 deviceRoot 的元类。我通过将类切换到 Java 而不是 Groovy 解决了这个问题。