File tree Expand file tree Collapse file tree
mockito-unit-test/src/test/java/in28minutes/powermock Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package in28minutes .powermock ;
2+
3+ import org .junit .Test ;
4+ import org .junit .runner .RunWith ;
5+ import org .mockito .InjectMocks ;
6+ import org .mockito .Mock ;
7+ import org .powermock .api .mockito .PowerMockito ;
8+ import org .powermock .core .classloader .annotations .PrepareForTest ;
9+ import org .powermock .modules .junit4 .PowerMockRunner ;
10+
11+ import java .util .ArrayList ;
12+
13+ import static org .junit .Assert .assertEquals ;
14+ import static org .mockito .Mockito .mock ;
15+ import static org .mockito .Mockito .stub ;
16+
17+ @ RunWith (PowerMockRunner .class )
18+ @ PrepareForTest ({ SystemUnderTest .class /*To be able to mock the Constructor, we need to add in the Class that creates the new object*/ })
19+ public class PowerMockitoMockingConstructorTest {
20+
21+ private static final int SOME_DUMMY_SIZE = 100 ;
22+
23+ @ Mock
24+ Dependency dependencyMock ;
25+
26+ @ InjectMocks
27+ SystemUnderTest systemUnderTest ;
28+
29+ @ Test
30+ public void powerMockito_MockingAConstructor () throws Exception {
31+
32+ ArrayList <String > mockList = mock (ArrayList .class );
33+
34+ stub (mockList .size ()).toReturn (SOME_DUMMY_SIZE );
35+
36+ PowerMockito .whenNew (ArrayList .class ).withAnyArguments ().thenReturn (mockList );
37+
38+ int size = systemUnderTest .methodUsingAnArrayListConstructor ();
39+
40+ assertEquals (SOME_DUMMY_SIZE , size );
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments