如何解决如何在来自其余模板的抛出异常下为 if else 条件编写 Junit
我是 Junit 的新手。我阅读了 Mockito 的基础知识。我不知道如何为测试代码覆盖率编写 Junit。 我正在使用 rest 模板调用来接收发送请求的响应对象。 我正在这里抛出的异常 (HttpStatusCodeException) 下执行一些逻辑。 下面是我的代码:
public void processData(Request data,HttpHeaders headers,String priority) throws JsonProcessingException {
try {
httpentity<Request> reqEntity = new httpentity<>(data,headers);
ResponseEntity<Response> helloResponse = restTemplate.postForEntity(someendpoint,reqEntity,Response.class);
if (priority.equals("low")) {
func1();
} else {
func2();
}
} catch (HttpStatusCodeException ex) {
if (ex.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE) && priority.equals("low")) {
func3();
} else if (ex.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE) && priority.equals("high")) {
func4();
}
else if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN) && priority.equals("low")) {
func5();
}
else if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN) && priority.equals("high")) {
func6();
}
else {
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(ex.getResponseBodyAsstring(),Response.class);
if (priority.equals("low")) {
func7();
} else {
func8();
}
}
}
}
}
得到一些帮助会很有帮助。
解决方法
按如下操作。
@Test
public void test1(){
Mockito.when(restTemplate.postForEntity(ArgumentMatchers.any(),ArgumentMatchers.any,ArgumentMatchers.<Class<Response>>any())).thenReturn(new ResponseEntity<>(new Response(),HttpStatus.ok));
//do your call and assertion
//processData( data,headers,priority)
}
异常覆盖测试
@Test
public void testException1(){
doThrow(HttpClientErrorException(HttpStatus.SERVICE_UNAVAILABLE).when(restTemplate).postForEntity(ArgumentMatchers.any(),ArgumentMatchers.<Class<Response>>any());
//do your call and assertion
//processData( data,"low")
}
@Test
public void testException2(){
doThrow(HttpClientErrorException(HttpStatus.FORBIDDEN).when(restTemplate).postForEntity(ArgumentMatchers.any(),"low")
}
@Test
public void testException3(){
doThrow(HttpClientErrorException(HttpStatus.SERVICE_UNAVAILABLE).when(restTemplate).postForEntity(ArgumentMatchers.any(),ArgumentMatchers.<Class<Response>>any());
//do your call and assertion
//processData( data,"high")
}
@Test
public void testException4(){
doThrow(HttpClientErrorException(HttpStatus.FORBIDDEN).when(restTemplate).postForEntity(ArgumentMatchers.any(),"high")
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。