问题描述
我是 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")
}