I have the following class where, in the constructor, I call another constructor to build a field of the class:
public class ClassIWantToTest {
private ClassIWantToMock anotherClass;
public ClassIWantToTest() {
//some stuff
anotherClass = new ClassIWantToMock(); //<-- call constructor to build the field
//some other stuff
}
}
When I test the class ClassIWantToTest
, I want to mock the instance of ClassIWantToMock
.
Hence, I've set up my test as follows:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassIWantToMock.class)
public class ClassIWantToTest_Test {
@Test
public void myFirstTest() {
ClassIWantToMock myMock = PowerMockito.mock(ClassIWantToMock.class);
PowerMockito.whenNew(ClassIWantToMock.class).withAnyArguments().thenReturn(myMock);
ClassIWantToTest test = new ClassIWantToTest(); //<-- not mocked
}
}
However, in the last line of code in the test (where I make a new
of the class I want to test), the constructor of ClassIWantToMock
is still called.
I've searched other examples on Stack Overflow (and in documentation), but it seems that it should be done like this. What am I forgetting/doing wrong?