Search code examples
javajmockit

How to mock private getters?


I have a class that I want to test. It looks similar to this:

public class ClassUnderTest
{
    private Dependency1 dep1;

    private Dependency1 getDependency1()
    {
       if (dep1 == null)
          dep1 = new Dependency1();
       return dep1;
     }

    public void methodUnderTest()
    {
       .... do something
       getDependency1().InvokeSomething(..);
    }
}

Class Dependency1 is complex and I would like to mock it out when writing a unit test for methodUnderTest().

How do I do that?


Solution

  • It's very easy, and there is no need to mock a private method or change the class under test:

    @Test
    public void exampleTest(@Mocked final Dependency dep) {
        // Record results for methods called on mocked dependencies, if needed:
        new Expectations() {{ dep.doSomething(); result = 123; }}
    
        new ClassUnderTest().methodUnderTest();
    
        // Verify another method was called, if desired:
        new Verifications() {{ dep.doSomethingElse(); }}
    }