0

我是开发微服务应用程序后端的新手。

我正在尝试从 Spring Boot 微服务架构中的其他服务获取国家/地区详细信息。作为单元测试的一部分,我正在编写一个否定测试用例,其中我请求的 CommonData mricroservice 在传递不存在的国家代码时将返回 http 状态 NOT FOUND。

但是 ResponseEntity 抛出了 HttpClientErrorExeption$NotFound: 404: [no body]。

我应该如何处理这种预期的反应?

CommonData 微服务 - 控制器

@RestController
@RequestMapping("countries")
public class CountryController {

    CountryService countryService;

    @Autowired
    CountryController(CountryService countryService) {
        this.countryService = countryService;
    }

    ...
    ...
    ...

    @GetMapping(path = "/{code}", produces = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public ResponseEntity<Country> getCountry(@Valid @PathVariable String code) {
        Country country = countryService.getCountry(code);
        if(country == null)
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        return new ResponseEntity<>(country, HttpStatus.FOUND);
    }
}

用户微服务 - CommonDataService

Country getCountryByCode(String code) throws Exception {
    String path = BASE_PATH + "/" + code;
    InstanceInfo instance = eurekaClient.getApplication(serviceId)
                                        .getInstances().get(0);
    
    String host = instance.getHostName();
    int port = instance.getPort();
    
    URI uri = new URI("http", null, host, port, path, null, null);
    RequestEntity<Void> request = RequestEntity.get(uri)
                                .accept(MediaType.APPLICATION_JSON).build();
    
    ResponseEntity<Country> response = restTemplate.exchange(request, Country.class);
    
    if(response.getStatusCode() != HttpStatus.FOUND)
        return null;
    
    return response.getBody();
}

负测试用例

@Test
void shouldReturnNullWhenInvalidCountryCodePassed() throws Exception {
    String countryCode = "GEN";
    Country actual = commonDataService.getCountryByCode(countryCode);
    assertNull(actual);
}

也欢迎任何改进代码的建议。

4

1 回答 1

0

试试 Junit 的 assertThrows

@ResponseStatus(code = HttpStatus.NOT_FOUND) 公共类 NotFoundException 扩展 RuntimeException {}

assertThrows(NotFoundException.class, ()->{objectName.yourMethod("not found")}

于 2020-10-03T12:38:57.057 回答