Search code examples
javamockitojunit4powermockito

Mockito: Mock private field initialization


How I can mock a field variable which is being initialized inline?

class Test {
    private Person person = new Person();
    ...
    public void testMethod() {
        person.someMethod();
        ...
    }
}

Here I want to mock person.someMethod() while testing the Test.testMethod() method for which I need to mock initialization of person variable. Any clue?

Edit: I'm not allowed to modify Person class.


Solution

  • I already found the solution to this problem which I forgot to post here.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ Test.class })
    public class SampleTest {
    
    @Mock
    Person person;
    
    @Test
    public void testPrintName() throws Exception {
        PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
        Test test= new Test();
        test.testMethod();
        }
    }
    

    Key points to this solution are:

    1. Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)

    2. Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

    3. And finally mock the constructor for Person class:

      PowerMockito.mockStatic(Person.class); PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);