Java 如何处理在客户端服务中找不到的状态
我是开发微服务应用程序后端的新手 我正在尝试从spring boot微服务架构中的其他服务获取国家详细信息。作为单元测试的一部分,我正在编写一个否定的测试用例,其中当传递一个不存在的国家代码时,我请求的CommonData mricroservice将返回http status NOT FOUND 但是,响应是抛出HttpClientErrorExeption$NotFound:404:[无正文] 我应该如何处理这些预期的反应 CommonData微服务-控制器Java 如何处理在客户端服务中找不到的状态,java,spring-boot,rest,microservices,spring-resttemplate,Java,Spring Boot,Rest,Microservices,Spring Resttemplate,我是开发微服务应用程序后端的新手 我正在尝试从spring boot微服务架构中的其他服务获取国家详细信息。作为单元测试的一部分,我正在编写一个否定的测试用例,其中当传递一个不存在的国家代码时,我请求的CommonData mricroservice将返回http status NOT FOUND 但是,响应是抛出HttpClientErrorExeption$NotFound:404:[无正文] 我应该如何处理这些预期的反应 CommonData微服务-控制器 @RestController
@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);
}
}
您也欢迎提出任何改进代码的建议。试试Junit的assertThrows @ResponseStatus(代码=HttpStatus.未找到) 公共类NotFoundException扩展RuntimeException{} assertThrows(NotFoundException.class,()->{objectName.yourMethod(“未找到”)}
@wak786“/countries”这是处理此类情况的标准方法吗?我的主要目标是检查返回的状态,如果找不到状态则返回null。我不希望异常流进入调用getCountryByCode(String)的方法。因此,测试应该检查null值,而不是是否引发异常。断言。assertNull(getCountryByCode(String));您可以尝试assertNull检查测试中的null值
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);
}