gpt4 book ai didi

java - 模拟 POST HTTP 请求获取空指针异常

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:00 26 4
gpt4 key购买 nike

我有这个方法

public HTTPResult post(String url, String requestBody) throws Exception {
return HTTPPostPut(url, requestBody, HttpMethod.POST);
}

public HTTPResult HTTPPostPut(String url, String requestBody,HttpMethod httpMethod) throws Exception {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("content-type","application/json");
HttpEntity requestEntity = new HttpEntity(requestBody,headers);

try {
ResponseEntity<String> response = this.restTemplate.exchange(url, httpMethod, requestEntity, String.class);
return new HTTPResult((String) response.getBody(), response.getStatusCode().value());
} catch (ResourceAccessException var8) {
String responseBody = var8.getCause().getMessage();
JSONObject obj = new JSONObject(responseBody);
return new HTTPResult(obj.getString("responseBody"), Integer.parseInt(obj.getString("statusCode")));
}
}

我为它创建了模拟并获取空指针异常:

public void testPost() throws Exception{
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("content-type","application/json");
HttpEntity requestEntity = new HttpEntity("{blbl}",headers);

ResponseEntity<String> response = new ResponseEntity("{blbl}", HttpStatus.OK);

RestTemplate mockRestTemplate = mock(RestTemplate.class);

when(mockRestTemplate.exchange(baseUrl, HttpMethod.POST, requestEntity, String.class)).thenReturn(response);

RestAPI api = new RestAPI(mockRestTemplate);

HTTPResult res = null;
try {
res = api.post(baseUrl,"{blbl}");
} catch (IOException e) {
e.printStackTrace();

}

assertEquals(res.getResponseBody(), "{blbl}");
assertEquals(res.getStatusCode(), HttpStatus.OK.value());
}

调用时出现空指针异常:

res = api.post(baseUrl,"{blbl}");

这是因为响应为空。

最佳答案

在安排模拟时使用参数匹配器,因为传递给模拟依赖项的实例与执行测试时传递的实例不同。

这将导致模拟返回空响应,因为预期实例不匹配

重构测试

public void testPost() throws Exception {
//Arrange
String expected = "{blbl}";
ResponseEntity<String> response = new ResponseEntity(expected, HttpStatus.OK);

RestTemplate mockRestTemplate = mock(RestTemplate.class);

when(mockRestTemplate.exchange(eq(baseUrl), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class)))
.thenReturn(response);

RestAPI api = new RestAPI(mockRestTemplate);

//Act
HTTPResult res = api.post(baseUrl, expected);

//Assert
assertEquals(res.getResponseBody(), expected);
assertEquals(res.getStatusCode(), HttpStatus.OK.value());
}

请注意 any(HttpEntity.class) 匹配器的使用,它将允许在调用时匹配传递的 HttpEntity

由于没有或全部使用参数匹配,因此 eq() 匹配器用于剩余的常量参数。

关于java - 模拟 POST HTTP 请求获取空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52915202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com