1+ package org .baeldung .mockito ;
2+
3+ import static org .mockito .Mockito .*;
4+ import static org .junit .Assert .assertThat ;
5+ import static org .hamcrest .Matchers .is ;
6+ import static org .hamcrest .Matchers .containsString ;
7+ import static org .apache .commons .lang3 .RandomStringUtils .randomAlphabetic ;
8+
9+ import org .junit .Test ;
10+ import org .junit .Rule ;
11+ import org .junit .rules .ExpectedException ;
12+ import org .mockito .MockSettings ;
13+ import org .mockito .exceptions .verification .TooLittleActualInvocations ;
14+ import org .mockito .invocation .InvocationOnMock ;
15+ import org .mockito .stubbing .Answer ;
16+
17+ public class MockitoMockTest {
18+ static class CustomAnswer implements Answer <Boolean > {
19+ @ Override
20+ public Boolean answer (InvocationOnMock invocation ) throws Throwable {
21+ return false ;
22+ }
23+ }
24+
25+ @ Rule
26+ public ExpectedException thrown = ExpectedException .none ();
27+
28+ @ Test
29+ public void whenUsingSimpleMock_thenCorrect () {
30+ MyList listMock = mock (MyList .class );
31+ when (listMock .add (anyString ())).thenReturn (false );
32+ boolean added = listMock .add (randomAlphabetic (6 ));
33+
34+ verify (listMock ).add (anyString ());
35+ assertThat (added , is (false ));
36+ }
37+
38+ @ Test
39+ public void whenUsingMockWithName_thenCorrect () {
40+ MyList listMock = mock (MyList .class , "myMock" );
41+ when (listMock .add (anyString ())).thenReturn (false );
42+ listMock .add (randomAlphabetic (6 ));
43+
44+ thrown .expect (TooLittleActualInvocations .class );
45+ thrown .expectMessage (containsString ("myMock.add" ));
46+
47+ verify (listMock , times (2 )).add (anyString ());
48+ }
49+
50+ @ Test
51+ public void whenUsingMockWithAnswer_thenCorrect () {
52+ MyList listMock = mock (MyList .class , new CustomAnswer ());
53+ boolean added = listMock .add (randomAlphabetic (6 ));
54+
55+ verify (listMock ).add (anyString ());
56+ assertThat (added , is (false ));
57+ }
58+
59+ @ Test
60+ public void whenUsingMockWithSettings_thenCorrect () {
61+ MockSettings customSettings = withSettings ().defaultAnswer (new CustomAnswer ());
62+ MyList listMock = mock (MyList .class , customSettings );
63+ boolean added = listMock .add (randomAlphabetic (6 ));
64+
65+ verify (listMock ).add (anyString ());
66+ assertThat (added , is (false ));
67+ }
68+ }
0 commit comments