How to mock a private function in JUnit


I have a main class Usuario that extends ( extends ) an abstract class called Sessao , and uses a function of Sessao called obterDados() that takes the session data and returns it in an object SessaoTO . I need to mock this function to return the mocked object and move on.

I have already tried to mock the Sessao class as follows:

// Declaração feita na classe
Sessao sessao;


// Declaração feita na função de teste
SessaoTO sessaoTO = new SessaoTO();


The problem is that at the time of execution it is giving NullPointer error because this mock is not working. I've already tried using @InjectMocks , but it did not work.

asked by anonymous 17.09.2018 / 17:39

1 answer


You can not mock a private method. The idea of mock is to provide false object implementations and not isolated methods (especially when private). In addition, a private method is by definition an internal functionality of an object hidden from the outside world. This is a thing like that snippet of code that in order not to get duplicate was isolated in a separate method. Therefore, there should be no reason to try to mock a private method.

The idea of mock testing is to provide the mock object with the mock implementations of the other objects it will interact with.

However, in your case, it seems like this is not what you're trying to do, but rather mock just some of the object's methods. This is not how it should be. Either the object contains the complete implementation you want to exercise or it is a mock. There is no middle ground.

So your problem is that you want to inject the SessaoTO that should be produced. This suggests that you could use the Strategy or Factory project design pattern. Instead of its Sessao object manufacturing SessaoTO in a private method, it would ask for the Strategy or the Factory injected into it. That way, you could mock this Strategy or Factory to provide the SessaoTO you want.

Other questions that I think are relevant to your case:

17.09.2018 / 20:50