doAnswer一般和when配合使用,当条件满足是,执行对应的Answer的answer方法,如果answer方法抛出异常,那么测试不通过。
这是我的一个实例:
import java.util.List; import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.mockito.Mockito.*; public class CustomAnswer implements Answer<String> { public String answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); Integer num = (Integer)args[0]; if( num>3 ){ return "yes"; } else { throw new RuntimeException(); } } @Test public void customAnswerTest(){ List<String> mock = mock(List.class); Mockito.doAnswer(new CustomAnswer()).when(mock).get(anyInt()); mock.get(4); mock.get(2); } }
当 mock.get(2); 的时候,执行判断,这个时候num>3 不成立,抛出异常,测试不通过。
answer方法中通过参数invocation能获取的东西是这些:一般判断方法的参数
public interface InvocationOnMock extends Serializable { /** * returns the mock object * * @return mock object */ Object getMock(); /** * returns the method * * @return method */ Method getMethod(); /** * returns arguments passed to the method * * @return arguments */ Object[] getArguments(); /** * calls real method * <p> * <b>Warning:</b> depending on the real implementation it might throw exceptions * * @return whatever the real method returns / throws * @throws Throwable in case real method throws */ Object callRealMethod() throws Throwable; }