Merge pull request from kwoyke/BAEL-3694

BAEL-3694: Refactor Mockito unit tests
This commit is contained in:
kwoyke 2020-03-06 13:43:24 +01:00 committed by GitHub
commit decc6825ec
1 changed files with 21 additions and 18 deletions
testing-modules/mockito/src/test/java/com/baeldung/mockito/voidmethods

View File

@ -16,48 +16,51 @@ public class MockitoVoidMethodsUnitTest {
@Test
public void whenAddCalledVerified() {
MyList mockVoid = mock(MyList.class);
mockVoid.add(0, "");
verify(mockVoid, times(1)).add(0, "");
MyList myList = mock(MyList.class);
myList.add(0, "");
verify(myList, times(1)).add(0, "");
}
@Test(expected = Exception.class)
public void givenNull_addThrows() {
MyList mockVoid = mock(MyList.class);
doThrow().when(mockVoid).add(isA(Integer.class), isNull());
mockVoid.add(0, null);
MyList myList = mock(MyList.class);
doThrow().when(myList).add(isA(Integer.class), isNull());
myList.add(0, null);
}
@Test
public void whenAddCalledValueCaptured() {
MyList mockVoid = mock(MyList.class);
MyList myList = mock(MyList.class);
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture());
mockVoid.add(0, "captured");
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
myList.add(0, "captured");
assertEquals("captured", valueCapture.getValue());
}
@Test
public void whenAddCalledAnswered() {
MyList mockVoid = mock(MyList.class);
doAnswer((Answer<Void>) invocation -> {
MyList myList = mock(MyList.class);
doAnswer(invocation -> {
Object arg0 = invocation.getArgument(0);
Object arg1 = invocation.getArgument(1);
//do something with the arguments here
assertEquals(3, arg0);
assertEquals("answer me", arg1);
return null;
}).when(mockVoid).add(any(Integer.class), any(String.class));
mockVoid.add(3, "answer me");
}).when(myList).add(any(Integer.class), any(String.class));
myList.add(3, "answer me");
}
@Test
public void whenAddCalledRealMethodCalled() {
MyList mockVoid = mock(MyList.class);
doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class));
mockVoid.add(1, "real");
verify(mockVoid, times(1)).add(1, "real");
MyList myList = mock(MyList.class);
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
myList.add(1, "real");
verify(myList, times(1)).add(1, "real");
}
}