0

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?

Matteo NNZ
  • 11,930
  • 12
  • 52
  • 89

1 Answers1

0

It was indeed a simple mistake. If the class ClassIWantToMock is initialized inside ClassIWantToTest, then also ClassIWantToTest should be prepared for test.

I replaced this:

@PrepareForTest(ClassIWantToMock.class)

with this:

@PrepareForTest({ClassIWantToTest.class,ClassIWantToMock.class})

... and it worked fine.

Matteo NNZ
  • 11,930
  • 12
  • 52
  • 89