1+ package org .mewx .practice .javamockito ;
2+
3+ import org .junit .Before ;
4+ import org .junit .Test ;
5+ import org .junit .runner .RunWith ;
6+ import org .mockito .*;
7+ import org .mockito .runners .MockitoJUnitRunner ;
8+
9+ import java .util .ArrayList ;
10+ import java .util .List ;
11+
12+ import static org .junit .Assert .*;
13+ import static org .mockito .Matchers .eq ;
14+ import static org .mockito .Mockito .times ;
15+ import static org .mockito .Mockito .verify ;
16+
17+ @ RunWith (MockitoJUnitRunner .class )
18+ public class ServiceCallerTest {
19+ @ InjectMocks
20+ private ServiceCaller serviceCaller = new ServiceCaller ();
21+ @ Spy
22+ private Service serviceInside = new Service (); // NOTE: cannot apply to new Service() objects inside methods // TODO: try PowerMockito
23+ @ Captor
24+ private ArgumentCaptor <List <String >> argCaptor ;
25+
26+ private Message message ;
27+ private ArrayList <String > list ;
28+
29+ @ Before
30+ public void setUp () {
31+ // Note: for JUnit 4.5+, no need to initMocks() any more
32+ message = new Message ();
33+ list = new ArrayList <>();
34+ list .add ("Initial item" );
35+ }
36+
37+ @ Test
38+ public void callServiceWithOneInList () {
39+ serviceCaller .callService (list , message );
40+ verify (serviceInside , times (1 )).runService (argCaptor .capture (), eq (message ));
41+ assertEquals (1 , argCaptor .getValue ().size ());
42+ assertEquals (1 , message .getSize ());
43+ assertEquals (Service .ERROR_MSG , message .getMessageAt (0 ));
44+ }
45+
46+ @ Test
47+ public void callServiceWithTwoInList () {
48+ list .add ("Another item" );
49+
50+ serviceCaller .callService (list , message );
51+ verify (serviceInside , times (1 )).runService (argCaptor .capture (), eq (message ));
52+ assertEquals (2 , argCaptor .getValue ().size ());
53+ assertEquals (0 , message .getSize ());
54+ }
55+ }
0 commit comments