Search code examples
javajunitmockitopowermockspring-test

how to mock a private method under a injectmocks annotated class in java


I meet a question about the mock private method in a injected mock annotated class. My code is like following

public class foo {
    @Autowired
    fooBean fooBean;

    public void method1() {
        this.method2();
    }

    private void method2() {
        fooBean.someMethod();
        system.out.println("Hello world");
    }
}

when I create a UT class with powermockito, the foo class should be @injectMocks, since the fooBean should be injected as mock class. But when foo class is marked as @injectMocks, it can't be mock its private method using like "doReturn("xxx").when(foo,"method2")", it will raise error about this can not be applied to injectMocks.

It is blocked. Don't know how to continue.


Solution

  • TLDR; you cannot use InjectMocks to mock a private method.

    You should mock out implementation details and focus on the expected behaviour of the application. It is important as well that the private methods are not doing core testing logic in your java project.

    Focus on writing functions such that the testing is not hindered by the private method. If it is not possible, it is worth asking what is the private method doing that is so valuable to your function and why it has to be private.

    There are other ways to test private methods - You could use the Reflections java library, this would let you stop methods at runtime and inject specific values into them. But, again, this is finding a solution to a problem that does not need to exist.