java Spring Boot / Mockito:正在模拟RestTemplate,但响应始终为空

jk9hmnmh  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(265)

我在使用Mockito时模拟测试类的响应对象时遇到问题。我正在尝试测试一个异常,为此,我需要从POST请求返回的类的属性之一。我已经成功地模拟了RestTemplate,但我的时间().然后返回()没有返回任何东西,我在“if”验证时得到了一个空指针异常。如果有人能帮助我解决这个问题,我将非常感激。
以下是我的服务类:

@Service
public class CaptchaValidatorServiceImpl implements CaptchaValidatorService{
   private static final String GOOGLE_CAPTCHA_ENDPOINT = "someEndpoint";
   private String stage;
   private String captchaSecret;
   private RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

   @Override
   public void checkToken(String token) throws Exception{
      MultiValueMap<String,String>  requestMap = new LinkedValueMap<>();
      requestMap.add("secret", captchaSecret);
      requestMap.add("response", token);
      try{
         CaptchaResponse response = restTemplate.postForObject(GOOGLE_CAPTCHA_ENDPOINT,
               requestMap, CaptchaResponse.class);
         if(!response.getSuccess()){
            throw new InvalidCaptchaTokenException("Invalid Token");
         }
      } catch (ResourceAccessException e){
         throw new CaptchaValidationNotPossible("No Response from Server");
      }
   }
   private SimpleClientHttpRequestFactory getClientHttpRequestFactory(){
      ...
   }
}

这是我的测试类:

@SpringBootTest
public class CaptchaValidatorTest{
   @Mock
   private RestTemplate restTemplate;
   @InjectMocks
   @Spy
   private CaptchaValidatorServiceImpl captchaValidatorService;
   private CaptchaResponse captchaResponse = mock(CaptchaResponse.class);

   @Test
   public void shouldThrowInvalidTokenException() {
      captchaResponse.setSuccess(false);
      Mockito.when(restTemplate.postForObject(Mockito.anyString(), 
           ArgumentMatchers.any(Class.class), ArgumentMatchers.any(Class.class)))
           .thenReturn(captchaResponse);
      Exception exception = assertThrows(InvalidCaptchaTokenException.class, () -> 
                captchaValidatorService.checkToken("test"));
      assertEquals("Invalid Token", exception.getMessage());
   }
}
1szpjjfi

1szpjjfi1#

在我看来,这可能是ArgumentMatchers的问题。方法postForObject需要参数,如字符串,MultiValueMap(或父)和类,但您在Mockito中设置。当:anyString()(正确)、any(Class.class)(但传递的是MultiValueMap-可能不正确)和any(Class.class)(正确)。
尝试用途:

Mockito.when(restTemplate.postForObject(ArgumentMatchers.any(String.class), 
           ArgumentMatchers.any(MultiValueMap.class), ArgumentMatchers.any(Class.class)))
           .thenReturn(captchaResponse);

编辑:在我看来,测试中的CaptchaResponse是不必要的模拟:

private CaptchaResponse captchaResponse = mock(CaptchaResponse.class);

但是如果你想要这样的话,我想你需要替换:

captchaResponse.setSuccess(false);

变成了这样:

Mockito.when(captchaResponse.getSuccess()).thenReturn(false);

相关问题