问题描述
我是开发微服务应用程序后端的新手。
我正在尝试从Spring Boot微服务架构中的其他服务获取国家/地区详细信息。作为单元测试的一部分,我正在编写一个否定测试用例,其中我要通过的CommonData mricroservice在传递不存在的国家/地区代码时将返回HTTP状态NOT FOUND。
但是ResponseEntity抛出HttpClientErrorExeption $ NotFound:404:[no body]。
我应该如何处理这种预期的反应?
CommonData MicroService-控制器
@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);
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);
}
也欢迎任何改进代码的建议。
解决方法
尝试assert抛出Junit
@ResponseStatus(代码= HttpStatus.NOT_FOUND) 公共类NotFoundException扩展了RuntimeException {}
assertThrows(NotFoundException.class,()-> {objectName.yourMethod(“ not found”))