【问题标题】:How to test Json correctly using mockmvc (Java)? What am I doing wrong?如何使用 mockmvc (Java) 正确测试 Json?我究竟做错了什么?
【发布时间】: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


【解决方案1】:

也可能是因为你的 Controller 方法接受的是 Spring 而不是 Object,你可以让 Spring 来处理它

我的控制器是这样的

@PostMapping
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public String processOrder(@RequestBody OrderDTO orderDTO)

只要您的对象(在我的情况下为 orderDTO)具有与您的 json 中的所有字段(具有相同名称)以及所有 getter、setter 和 allArgsConstructor 它应该工作

【讨论】:

  • 添加了使用 Gson 自动将对象转换为 JSON。结果是一样的
  • 请查看我的更新答案,如果有帮助请告诉我
  • 为测试添加了@Postmapping 注释。测试不通过,结果附上
  • 这不是关于使用对象而不是字符串作为参数的注释。您还可以更新代码,以便我可以看到它现在的样子。
  • 编辑控制器,方法 saveOrder。删除了所有业务逻辑。接收并返回一个对象。它应该工作?来自 Postman 的 post-query 作品。 Иге 测试没有通过
猜你喜欢
  • 1970-01-01
  • 2013-09-15
  • 2013-09-07
  • 2013-08-06
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2019-12-23
  • 2016-06-11
相关资源
最近更新 更多