如何在junit Springboot中测试私有方法

oza*_*oza 3 java junit mockito spring-boot

我需要测试私有方法。以下方法的正确测试方法是什么?我尝试使用 Mockito 时..但是我如何模拟私有方法。我认为我们不能模拟私有方法。

    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);
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 7

Spring Boot 没有什么特别之处:

不应测试私有方法 - 这是类的内部“方式”,您应该主要测试类的 API - 它通过非私有方法向类的用户公开的“功能”。

考虑将类视为黑盒(可能具有该类的模拟依赖项)并按照我的解释检查其功能。