verify(mock, timeout(timeout + delta).times(2)).callMethod(“test”);
// immediately success
verify(mock, timeout(10)).sayHello();
async.get();
// after() awaits full duration to check if verification passes
verify(mock, after(10).times(2)).callMethod(“test”);
verify(mock, after(10)).sayHello();
}
spy
spy 的官方定义是:
partial mocking, real methods are invoked but still can be verified and stubbed
会调用被 spy 的真实对象的方法,但仍能被 Mockiton 所直接用于 mock 和 verify,也就是说在没有配置 mock 行为的情况下默认是调用被 mock 对象的真实方法。
-
句式 doXxx…when 当同一目标方法上定义了多个 mock 行为,后序 mock 可以覆盖前序 mock
-
clearInvocations 仅清理之前的调用
-
reset 会重置为初始状态(所有中途的赋值都会被清理掉)
@Test
public void testDoReturn() {
// real creation
List list = new LinkedList();
List spy = spy(list);
//optionally, you can stub out some methods:
int mockSize = 100;
when(spy.size()).thenReturn(mockSize);
//size() method was stubbed - 100 is printed
assertEquals(spy.size(), mockSize);
// Overriding a previous exception-stubbing:
when(spy.size()).thenThrow(new IllegalStateException(“not init”));
doReturn(mockSize).when(spy).size();
assertEquals(spy.size(), mockSize);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
Assertions.assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> spy.get(0));
doReturn(“mock data”).when(spy).get(1);
//using the spy calls real methods
spy.add(“one”);
assertEquals(spy.get(0), “one”);
/*
Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
You are using a dependency injection framework to inject your mocks.
The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.
Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.
*/
clearInvocations(spy);
verify(spy, times(0)).add(“two”);
reset(spy);
when(spy.size()).thenReturn(0);
assertEquals(spy.size(), 0);
}
▐ PowerMock
以上介绍的是 Mockiton 中常用的API,而 PowerMock 则更强大,可以 mock static 方法,private 方法,final 方法,enum,构造函数调用等。
示例代码中用到的测试类如下:
public enum TypeEnum {
Y(“TRUE”),
N(“FALSE”);
private final String title;
TypeEnum(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public final class FinalTarget {
public FinalTarget() { }
public final String finalMethod() {
return “Hello final!”;
}
}
public class StaticTarget {
public static String firstMethod(String name) {
return “Hello " + name + " !”;
}
public static String secondMethod() {
return “Hello no one!”;
}
}
public class PartialTarget {
private String arg