Spring MVC 在mockito公寓测试中产生RestClientException错误

4jb9z9bj  于 2022-11-14  发布在  Spring
关注(0)|答案(2)|浏览(124)

我试图验证一个restclientexception错误。我的代码如下,如果您能提供帮助,我将不胜感激。这是我的测试类:'
`

@Test
void test_update_customer_in_ath0_server_error(){
    //given
    ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
    doReturn(responseEntity)
            .when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), (Class<String>)any());

    idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto);

    //then
    verify(restTemplate).exchange(any(), eq(HttpMethod.PATCH), argThat(this::verifyUpdatedCustomerBody), (Class<String>)any());
}

这是从我的injectMock类中得到的
`

try {
    response = restTemplate.exchange(URI.create(idpFacadeUpdateUrl), HttpMethod.PATCH, entity,  String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        log.info("customer first name update success {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
    }else {
        log.error("Customer first name update failed in IDP for {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
    }
} catch (RestClientException e) {
    throw new RestClientException("Idp facade API error for user first name " + customerUpdateRecordsDto.getFirstName(), e);
}

`

nbysray5

nbysray51#

如果您使用的是JUnit 5,请尝试将最后一行替换为如下内容:

assertThrows(RestClientException.class, () -> idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto));

在JUnit 4中,@Test注解提供了一个参数,用于指定测试的预期异常。

xmq68pz9

xmq68pz92#

exchange方法被调用时,你可以让你的模拟抛出一个异常:

doThrow(new RestClientException())
            .when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), eq(String.class));

然后使用assertThrowsassertThatCode(…).hasMessageContaining(…)验证catchblock中引发的新异常。

相关问题