【发布时间】:2020-08-06 19:37:39
【问题描述】:
我刚刚开始学习 Spring。
控制器接受并返回 Json。我无法测试它。
控制器
@RestController
@RequestMapping("/service")
@Slf4j
public class OrderController {
private final OrderService orderService;
private final ConvertService convertService;
@Autowired
public OrderController(OrderService orderService, ConvertService convertService) {
this.orderService = orderService;
this.convertService = convertService;
}
@GetMapping
public String getOrderList(@RequestBody String json) {
String customer = convertService.toOrder(json).getCustomer();
List<Order> orderList = orderService.findOrderListByCustomer(customer);
return convertService.toJson(orderList);
}
@PostMapping
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public String saveOrder(@RequestBody OrderDTO orderDTO) throws JsonProcessingException {
return objectMapper.writeValueAsString(orderDTO)
}
}
控制器测试
@SpringBootTest
@AutoConfigureMockMvc
class OrderControllerTest {
@Autowired
private MockMvc mvc;
private String json;
@BeforeEach
public void setData() {
json = new Gson().toJson(new OrderDTO ("user1",23));
}
@Test
void getJsonTest() throws Exception {
mvc.perform(MockMvcRequestBuilders
.get("/sb/service")
.header("Accept","application/json")
.contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
@Test
void postJsonTest() throws Exception {
mvc.perform(MockMvcRequestBuilders
.post("/sb/service")
.header("Accept","application/json")
.contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
}
测试时,我总是得到 404。但是如果我从 Postman 发送请求,则响应是 200。 我研究了这个答案,但没有帮助 How to check JSON response in Spring MVC test
测试结果
MockHttpServletRequest:
HTTP Method = POST
Request URI = /sb/service
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"30"]
Body = {"customer":"user1","cost":23}
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<404>
Expected :200
Actual :404
【问题讨论】:
-
欢迎来到 SO!您可以在设置 mockMvc 的地方分享您的代码吗?路径真的匹配吗?您的控制器路径是否有一些通用前缀,例如
api/v1或者它真的映射到/sb/service? -
您没有包含接受标头。另外为什么要手动转换为/从字符串? Spring 会为您完成所有这些,不确定您为什么需要手动转换(看起来您正在解决而不是使用框架)。如果添加标题没有帮助,请添加完整的测试用例,而不仅仅是测试方法。
-
添加了代码。公共前缀仅适用于应用程序 /sb。如果您从 Postman 发送请求,则控制器正常工作
-
M. Deinum,我更正了代码,但结果是一样的
标签: json spring rest testing mockmvc