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);
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With