Search code examples
junitmockingmockitoprotected

How do I use Mockito to mock a protected method?


I’m using Mockito 1.9.5. How do I mock what is coming back from a protected method? I have this protected method …

protected JSONObject myMethod(final String param1, final String param2)
{
…
}

However, when I attempt to do this in JUnit:

    final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);        
    final String pararm1 = “param1”;
    Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);

On the last line, I get a compilation error “The method ‘myMethod’ is not visible.” How do I use Mockito to mock protected methods? I’m open to upgrading my version if that’s the answer.


Solution

  • This is not an issue with Mockito, but with plain old java. From where you are calling the method, you don't have visibility. That is why it is a compile-time issue instead of a run-time issue.

    A couple options:

    • declare your test in the same package as the mocked class
    • change the visibilty of the method if you can
    • create a local (inner) class that extends the mocked class, then mock this local class. Since the class would be local, you would have visibility to the method.