在Mockito没有调用的模拟方法

时间:2013-10-31 21:42:51

标签: java spring junit mockito

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

@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对象永远不会被返回,我已经没有想法了。有人能告诉我为什么会这样吗?也许我错过了一些东西:/

更新:

所以我更新了我的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();
}

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

1 个答案:

答案 0 :(得分:7)

这是问题所在:

ReCaptchaImpl reCaptcha = new ReCaptchaImpl();

那只是创建一个新实例 - 你的模拟器根本就没用过。请注意你是如何将模拟传递给任何东西的 - 你是如何期望生产代码使用它的?

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

可以使用PowerMock,但我建议重新设计以避免需要模拟,或者允许在某处注入依赖项。