Java 使用Spring Boot TestRestTemplate相对路径强制JSON转换

Java 使用Spring Boot TestRestTemplate相对路径强制JSON转换,java,rest,testing,spring-boot,Java,Rest,Testing,Spring Boot,根据弹簧靴: 请注意,testrestemplate现在可以作为bean随时使用 使用了@SpringBootTest。它已预先配置为解析相对路径 到http://localhost:${local.server.port}。我们也可以使用 @LocalServerPort注释,以插入服务器所使用的实际端口 正在运行到测试场 我有一个返回XML数据的RESTFul应用程序。POM文件包含测试类中的jackson dataformat xml,我有以下代码: @RunWith(SpringRunn

根据弹簧靴:

请注意,
testrestemplate
现在可以作为bean随时使用 使用了
@SpringBootTest
。它已预先配置为解析相对路径 到<代码>http://localhost:${local.server.port}。我们也可以使用
@LocalServerPort
注释,以插入服务器所使用的实际端口 正在运行到测试场

我有一个返回XML数据的RESTFul应用程序。POM文件包含测试类中的
jackson dataformat xml
,我有以下代码:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class XMLDataTest {

    @Autowired
    private TestRestTemplate restTemplate;
    ...
    ResponseEntity<List<City>> cities = restTemplate.exchange(appPath,
        HttpMethod.GET, null, paramType);

    assertThat(cities.getBody()).hasSize(8);
    assertThat(cities.getBody()).contains(this.c1, this.c2, this.c3);

如何修复此问题?

API返回一个JSON对象,您需要一个JSON数组,因此出现异常。要使其返回XML,需要指定请求的Accept标头

有用的技巧:调试此类问题时,使用String.class作为预期的响应类型,并打印结果

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);

HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

ResponseEntity<List<City>> cities = restTemplate.exchange(appPath,
           HttpMethod.GET, entity, paramType);
HttpHeaders=newhttpheaders();
headers.setContentType(MediaType.APPLICATION\uXML);
HttpEntity=新的HttpEntity(“参数”,标题);
ResponseEntity cities=restemplate.exchange(appPath,
HttpMethod.GET,实体,参数类型);

API返回一个JSON对象,您需要一个JSON数组,因此出现异常。要使其返回XML,需要指定请求的Accept标头

有用的技巧:调试此类问题时,使用String.class作为预期的响应类型,并打印结果

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);

HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

ResponseEntity<List<City>> cities = restTemplate.exchange(appPath,
           HttpMethod.GET, entity, paramType);
HttpHeaders=newhttpheaders();
headers.setContentType(MediaType.APPLICATION\uXML);
HttpEntity=新的HttpEntity(“参数”,标题);
ResponseEntity cities=restemplate.exchange(appPath,
HttpMethod.GET,实体,参数类型);

询问异常时,始终发布异常的准确完整堆栈跟踪。添加了异常。我认为这是一个配置问题。当询问异常时,始终发布异常的准确和完整的堆栈跟踪。好的,添加了完整的堆栈跟踪。您的API(我们没有源代码)确实返回JSON(可能是因为请求指定它接受JSON作为响应类型),但它返回JSON对象,您需要一个JSON数组(即列表)。当询问异常时,始终发布异常的准确和完整堆栈跟踪。添加了异常。我认为这是一个配置问题。当询问异常时,始终发布异常的准确和完整的堆栈跟踪。好的,添加了完整的堆栈跟踪。您的API(我们没有源代码)确实返回JSON(可能是因为请求指定它接受JSON作为响应类型),但它返回JSON对象,您需要一个JSON数组(即列表)。