gpt4 book ai didi

java - Mockito 中未调用模拟方法

转载 作者:行者123 更新时间:2023-12-02 18:23:43 26 4
gpt4 key购买 nike

您好,我有一个带有方法的服务:

@Service
public class CaptchaServiceImpl implements CaptchaService {

@Autowired
private MessageSource messageSource;

@Override
public boolean processCaptcha(String requestedUrl, String challenge, String userResponse) {

ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey(messageSource.getMessage("reCaptcha.private.key", new Object[]{}, new Locale("pl", "PL")));
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(requestedUrl, challenge, userResponse);

return reCaptchaResponse.isValid();
}

}

我为它编写了一个测试:

@RunWith(MockitoJUnitRunner.class)
public class CaptchaServiceImplTest {

private CaptchaService captchaService;

@Mock
private MessageSource messageSource;

@Mock
private ReCaptchaImpl reCaptcha;

@Before
public void init() {
captchaService = new CaptchaServiceImpl();
ReflectionTestUtils.setField(captchaService, "messageSource", messageSource);
}

@Test
public void shouldPassReCaptchaValidation() {
ReCaptchaTestResponse captchaResponse = new ReCaptchaTestResponse(true, "no errors");
when(messageSource.getMessage("reCaptcha.private.key", new Object[]{}, new Locale("pl", "PL"))).thenReturn("reCaptcha.private.key");
when(reCaptcha.checkAnswer(anyString(), anyString(), anyString())).thenReturn(captchaResponse);

boolean reCaptchaResponse = captchaService.processCaptcha("url", "challenger", "userResponse");

assertThat(reCaptchaResponse, is(true));
}

private class ReCaptchaTestResponse extends ReCaptchaResponse {

protected ReCaptchaTestResponse(boolean valid, String errorMessage) {
super(valid, errorMessage);
}
}

}

ReCaptchaResponse 是 protected 类...

因此,当我运行测试时,我得到:

 java.lang.AssertionError: 
Expected: is <true>
got: <false>

由于某种原因,我的模拟方法 checkAnswer 从未被调用,我的 captchaResponse 对象也从未返回,我已经不知道为什么了。有人能告诉我为什么会这样吗?也许我错过了一些东西:/

更新:

所以我更新了我的 CaptchaService:

@Autowired
private ReCaptchaImpl reCaptcha;

@Override
public boolean processCaptcha(String requestedUrl, String challenge, String userResponse) {
reCaptcha.setPrivateKey(messageSource.getMessage("reCaptcha.private.key", new Object[]{}, new Locale("pl", "PL")));
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(requestedUrl, challenge, userResponse);

return reCaptchaResponse.isValid();
}

现在测试是绿色的! :)谢谢

最佳答案

这就是问题:

ReCaptchaImpl reCaptcha = new ReCaptchaImpl();

这只是创建一个新实例 - 您的模拟根本没有被使用。请注意,您没有将模拟传递给任何东西 - 您期望生产代码如何使用它?

模拟非常适合注入(inject)的依赖项,甚至是工厂返回的依赖项,您可以让工厂为您返回模拟 - 但您只是调用构造函数。

可以使用PowerMock为此,但我建议重新设计以避免根本需要模拟,或者允许将依赖项注入(inject)到某个地方。

关于java - Mockito 中未调用模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19717129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com