繁体   English   中英

Spring Boot如何测试控制器响应

[英]Spring boot how to test controller response

我尝试测试控制器的响应。 我写了简单的测试

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());

测试结果:

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

我的问题是如何测试控制器返回的响应是否正确? 我尝试在地图和字符串(如上所示)上执行此操作,但它们都无法正常工作

您应该使用 Spring 的MockMvc对您的 Web 层发出请求。 您可以参考Spring 的这份入门指南

暂无
暂无

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

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