您好,我有一个服务方法:
@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 是受保护的类...
因此,当我运行测试时,我得到:
java.lang.AssertionError:
Expected: is <true>
got: <false>
出于某种原因,我的模拟方法 checkAnswer 从未被调用,我的 captchaResponse 对象也从未返回,我已经没有想法为什么了。有人可以告诉我为什么会这样吗?也许我错过了一些东西:/
更新:
所以我更新了我的验证码服务:
@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();
}
现在测试是绿色的!:) 谢谢