【发布时间】:2019-02-14 17:08:18
【问题描述】:
我正在为 Spring-Boot 应用程序编写组件测试,以测试我的安全配置。因此,我正在运行应该测试成功响应和“禁止”状态的测试。 我遇到的问题是,因为我的 REST 调用需要一个复杂的 JSON,所以对于阻塞的调用,测试会失败,因为 TestRestTemplate 正在尝试反序列化不存在的响应主体。
我正在运行一个 Spring-Boot 应用程序,并且测试类被注释为:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
我正在尝试测试应该返回用户列表的 REST API。 调用的简化版本是:
ResponseEntity<List<User>> responseEntity = testRestTemplate.exchange(URL, HttpMethod.GET, entity, new ParameterizedTypeReference<List<User>>() {});
其中 TestRestTemplate 由 Spring 自动装配,实体包含授权信息。
对于未经授权的请求,我收到如下错误:
org.springframework.web.client.RestClientException: Error while extracting response for type [java.util.List<my.package.User>] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 1]
如果我将响应实体更改为接收字符串而不是列表,我会收到响应并可以检查状态并看到它是“禁止的”
ResponseEntity<String> responseEntity = testRestTemplate.exchange(URL, HttpMethod.GET, null, String.class);
我知道我可以通过以下方式解决这个问题:
- 使用字符串和 Gson 反序列化,或
- 使用 RestTemplate 代替 TestRestTemplate 并处理 HttpStatusCodeException,或者
- 在状态码不是 2xx 时不尝试反序列化的覆盖方法
但由于 TestRestTemplate 应该是一个容错便利子类,我本来希望它开箱即用,而不是尝试反序列化错误响应。
我在这里遗漏了什么吗?我用错了吗?
【问题讨论】:
-
>2 年后,这对我来说也是一个问题。如果 HttpResponse 不是 200,您会期望
TestRestTemplate不会尝试将错误反序列化到复杂对象中...
标签: java spring spring-boot resttemplate spring-boot-test