这里总结几个我做个test的用法。
1. argument matcher, such as anyInt(); when .. thenreturn..; verify never(), atleast(), atmost()
List mock = mock(List.class);
/*
* stub the mock. with return value, will be" when ...", then
* " thenReturn...". without return value, will be " do
*/
//
when(mock.get(anyInt())).thenReturn("123");
// simulate void function,
doThrow(new RuntimeException("test the error")).when(mock).clear();
mock.get(123);
verify(mock).get(anyInt());
mock.add("1");
mock.add("2");
mock.add("2");
verify(mock).add("1");
verify(mock, times(2)).add("2");
// will fail, because three times will be invoked
// verify(mock).add(anyString());
verify(mock, never()).add("3");
verify(mock, atLeastOnce()).add("1");
verify(mock, atMost(5)).add("2");
mock.clear();
2.Inorder,验证顺序和执行次数
List target = mock(List.class);
target.add("1");
target.add("2");
InOrder inOrder = inOrder(target);
inOrder.verify(target).add("1");
inOrder.verify(target).add("2");
List seq1 = mock(List.class);
List seq2 = mock(List.class);
List seq3 = mock(List.class);
seq1.add("123");
seq2.add("123");
InOrder inOrder2 = inOrder(seq1, seq2);
// inOrder2.verify(seq1).add("123");
// inOrder2.verify(seq2).add("123");
inOrder2.verify(seq1).add("123");
inOrder2.verify(seq2).add("123");
verify(seq1).add("123");
verifyZeroInteractions(seq3);
verifyNoMoreInteractions(seq1);
3.Answer
TestInterface testTarget = mock(TestInterface.class,
new Answer<TestInterface>() {
@Override
public TestInterface answer(InvocationOnMock invocation)
throws Throwable {
Object[] arguments = invocation.getArguments();
// based on arguments, you can return different value
System.out.println(arguments.length);
return null;
}
});
testTarget.print4();
testTarget.print4("2");
testTarget.print4("3", "4");
testTarget.print4("4");
这里利用Answer可以根据传入的参数,返回不同的值,从而以可以利用一个mock对象对一个方法mock多个不同的返回值。
4.spy
TestInterface inte = new ConcreteTestInterface2();
TestInterface spy = spy(inte);
when(spy.print2()).thenReturn(333);
// if you want to call orignal implementation, you can call
// doCallRealMethod
doCallRealMethod().when(spy).print2();
System.out.println(spy.print1("123"));
System.out.println(spy.print2());
System.out.println(spy.print3());