3

I need to test private method. What is the correct way of testing below method? I tried using Mockito when.. but how do I mock a private method. I think we cannot Mock private method.

    private classObject privateMethod(Message message){
        try{
           Objectmapper mapper = new ObjectMapper();
           return mapper.readValue(message.getBody(), ClassName.class);
        }catch(){
           throw new Exception(); 
        }
    }

    //I am getting an exception while testing

    byte[] body = {10,-11,12,14,15};
    MessageProperties msgProp = new MessageProperties();
    Message message = new Message(body, msgProp);

    // the above message is passed as parameter to function through                           
    // which private method is called
    objectxyz.execute(message);

    // execute method
    public void execute(Message message){
        objectxyz xyz = privateMethod(message);
        objectabc abc = service.someMethod(xyz);
        List<object> list = someAnotherMethod(abc, xyz);
    }

    // I tried below code in my test case and have used 
    // @Mock private ObjectMapper objectMapper;
    Mockito.when(objectMapper.readValue(body, ClassName.class)).thenReturn(classObject);
oza
  • 51
  • 1
  • 1
  • 9
  • Okay now I understand the concept, but if we want to test public method i.e execute which includes return of private method and private methods return mapper.readValue(message.getBody(), ClassName.class); is failing how can we achieve successful test for execute method? – oza Apr 22 '20 at 08:34

4 Answers4

6

Spring boot has nothing special about it:

Private methods should not be tested - it's an internal "how" of the class and you should mainly test the API of the class - the "capabilities" that it exposes to the user of the class via non-private methods.

Consider treat a class as a black box (with possibly mocked dependencies of this class) and check its functionality as I've explained.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
2

You can use the manifold framework to test with reflection. See this previously answered solution: How do I test a private function or a class that has private methods, fields or inner classes?

Neal Kumar
  • 46
  • 3
2

These are Basic basic approaches to test private methods.

  1. Don't test private methods.
  2. Give the methods package access.
  3. Use a nested test class.
  4. Use reflection.

Detail article

Abhijit
  • 374
  • 3
  • 15
0

yup, private method should be a internal method, should use by another public method, so. do not test it;

rui.zhang
  • 11
  • 1