简体   繁体   English

Spring Boot如何测试控制器响应

[英]Spring boot how to test controller response

I try to test the response of the controller.我尝试测试控制器的响应。 I wrote simple test我写了简单的测试

String expectedResponse = "{price:type correct price}";

final String baseUrl = "http://localhost:"+randomServerPort+"/api/products/1";
URI uri = new URI(baseUrl);

ProductModel productModel = new ProductModel();
productModel.setPrice(-1.0);
productModel.setName("Logitech G-403");

HttpEntity<ProductModel> request = new HttpEntity<>(productModel);
ResponseEntity<String> result = this.restTemplate.postForEntity(uri, request, String.class);

assertEquals(400, result.getStatusCodeValue());
assertEquals(expectedResponse,result.getBody());

Test result:测试结果:

org.opentest4j.AssertionFailedError: 
Expected :{price:type correct price}
Actual   :{"price":"type correct price"}

My question is how to test if the response returned by the controller is correct?我的问题是如何测试控制器返回的响应是否正确? I tried to do it on the map and on the String (shown above) but neither of them works properly我尝试在地图和字符串(如上所示)上执行此操作,但它们都无法正常工作

You should use Spring's MockMvc for making requests against your web layer.您应该使用 Spring 的MockMvc对您的 Web 层发出请求。 You can refer to this getting started guide by Spring .您可以参考Spring 的这份入门指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM