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

时间:2015-06-12 14:55:33

标签: java unit-testing powermockito

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

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

当我运行测试时,java.lang.reflect.InvocationTargetExceptionNullPointerException方法的第二行显示isCaptchaValid,如下所示:

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对象。

1 个答案:

答案 0 :(得分:2)

问题已解决

致电

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忽略方法的主体并立即返回你想要的内容。