有些实现类是匿名的:
public interface Service { int doSomething(); }
public final class TestedUnit {
private final Service service = new Service() {
public int doSomething() { return 2; }
};
public int businessOperation() {
return service.doSomething();
}
}
使用@Capturing
标注基类/接口,所有实现类会被mock:
@Capturing Service anyService;
@Test
public void mockingImplementationClassesFromAGivenBaseType() {
new Expectations() {{
anyService.doSomething();
returns(3);
}};
int result = new TestedUnit().businessOperation();
assertEquals(3, result);
}
@Capturing
是@Mock
的增强版,有一个可选参数maxInstances
用于捕获前面指定数量的对象,其默认值为Integer.MAX_VALUE
。
@Test
public void TestMethod(@Capturing(maxInstances = 2) final Dependency dependency1,
@Capturing(maxInstances = 2) final Dependency dependency2,
@Capturing final Dependency remain) {
new NonStrictExpectations() {{
dependency1.getValue();
result = 1;
dependency2.getValue();
result = 2;
remain.getValue();
result = 3;
}};
assertEquals(1, new Dependency().getValue());
assertEquals(1, new Dependency().getValue());
assertEquals(2, new Dependency().getValue());
assertEquals(2, new Dependency().getValue());
assertEquals(3, new Dependency().getValue());
}
上面的@Capturing
是出现在参数列表中的,如果是作为field声明的,maxInstances
会失效,@Capturing
退化为@Mock
。
网友评论