【发布时间】:2020-10-03 20:38:57
【问题描述】:
我是开发微服务应用后端的新手。
我正在尝试从 Spring Boot 微服务架构中的其他服务获取国家/地区详细信息。作为单元测试的一部分,我正在编写一个否定测试用例,其中我请求的 CommonData 微服务将在传递不存在的国家代码时返回 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();
}
NegativeTestCase
@Test
void shouldReturnNullWhenInvalidCountryCodePassed() throws Exception {
String countryCode = "GEN";
Country actual = commonDataService.getCountryByCode(countryCode);
assertNull(actual);
}
也欢迎任何改进代码的建议。
【问题讨论】:
-
@wak786 "/countries"
标签: java spring-boot rest microservices spring-resttemplate