java – 为什么模拟私有方法进入方法?

我在测试中使用PowerMockito来模拟私有方法.

validator = spy(new CommentValidator(form, request));
PowerMockito.when(
        validator,
        method(CommentValidator.class, "isCaptchaValid",
        HttpServletRequest.class))
    .withArguments(Mockito.any())
    .thenReturn(true);

当我运行测试时,我在isCaptchaValid方法的第二行获得了带有NullPointerException的java.lang.reflect.InvocationTargetException,如下所示:

private boolean isCaptchaValid(HttpServletRequest request) {
    Captcha captcha =
        (Captcha) request.getSession().getAttribute("attribute");
    if (captcha == null) {
        log.debug(String.format("O valor do captcha da sessão esta nulo. IP: [%s]",
            IPUtil.getReaderIp(request)));
        return false;
    }
    if (captcha.isInputValid(
            request.getParameter("captcha").toString().toUpperCase())) {
        return true;
    }
    return false;
}

public final Boolean isInputValid(String pInput) {

    if (getPuzzle() == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("puzzle is null and invalid. Will return Boolean.FALSE");
        }
        return Boolean.FALSE;
    }

    Boolean returnValue = verifyInput(pInput);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Validation of puzzle: " + returnValue);
    }
    disposePuzzle();

    return returnValue;
}

如果我嘲笑它的行为,为什么要考虑方法的实现呢?有没有办法避免这种情况?我需要模拟它的原因是因为我无法提供Captcha对象.

最佳答案 问题解决了

通过电话

PowerMockito.when(
        validator,
        method(CommentValidator.class, "isCaptchaValid",
        HttpServletRequest.class))
    .withArguments(Mockito.any())
    .thenReturn(true);

首先,方法本身由PowerMockito验证,因此很可能找到NPE.

为了避免这种情况,您需要反转该逻辑.

doReturn(true).when(validator, "isCaptchaValid", any(HttpServletRequest.class));

它使PowerMockito忽略了方法的主体并立即返回你想要的东西.

点赞