Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test private method in junit Springboot

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);
like image 732
oza Avatar asked Oct 20 '25 15:10

oza


2 Answers

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.

like image 186
Mark Bramnik Avatar answered Oct 23 '25 03:10

Mark Bramnik


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?

like image 26
Neal Kumar Avatar answered Oct 23 '25 05:10

Neal Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!