Mockito|Mockito mock void methods Example

@RunWith(MockitoJUnitRunner.class) public class StubbingTest {@Mock privateList list; @Before public void init() { list = mock(ArrayList.class); }@Test public void howToUseStubbing() { when(list.get(0)).thenReturn("first"); assertThat(list.get(0), equalTo("first")); when(list.get(anyInt())).thenThrow(new RuntimeException()); try { list.get(0); fail(); } catch (Exception e) { assertThat(e, instanceOf(RuntimeException.class)); } }@Test public void howToStubbingVoidMethod() { doNothing().when(list).clear(); doThrow(RuntimeException.class).when(list).clear(); try { list.clear(); fail(); } catch (Exception e) { assertThat(e, instanceOf(RuntimeException.class)); } }@Test public void stubbingReturn() { when(list.get(0)).thenReturn("first"); doReturn("second").when(list).get(1); assertThat(list.get(0), equalTo("first")); assertThat(list.get(1), equalTo("second")); }@Test public void stubbingWithAnswer() { when(list.get(anyInt())).thenAnswer(invocationOnMock -> { Integer index = invocationOnMock.getArgument(0, Integer.class); return String.valueOf(index * 10); }); assertThat(list.get(0), equalTo("0")); assertThat(list.get(10), equalTo("100")); assertThat(list.get(999), equalTo("9990")); }@Test public void iterateSubbing() { when(list.size()).thenReturn(1, 2, 3, 4, 5); assertThat(list.size(), equalTo(1)); assertThat(list.size(), equalTo(2)); assertThat(list.size(), equalTo(3)); assertThat(list.size(), equalTo(4)); assertThat(list.size(), equalTo(5)); assertThat(list.size(), equalTo(5)); }@Test public void stubbingServiceTest() { StubbingService stubbingService = mock(StubbingService.class); System.out.println(stubbingService.getClass()); stubbingService.gets(); }@After public void destroy() { reset(this.list); }}

    推荐阅读