java为什么要用私有方法_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忽略了方法的主体并立即返回你想要的东西.

标签:java,unit-testing,powermockito

来源: https://codeday.me/bug/20190702/1359573.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值