看看Mockito API文档。由于链接的文档提到(点#12),你可以使用任何的
doThrow(),doAnswer(),donothing(),doReturn()家人从框架的
Mockito的方法来嘲笑无效的方法。
例如,
Mockito.doThrow(new Exception()).when(instance).methodName();
或者如果你想将其与后续行为结合起来,
Mockito.doThrow(new Exception()).donothing().when(instance).methodName();
假设你要在
setState(String s)下面的
World类
doAnswer中模拟设置器,则代码使用方法来模拟
setState。
World mockWorld = mock(World.class); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); System.out.println("called with arguments: " + Arrays.toString(args)); return null; }}).when(mockWorld).setState(anyString());


