测试中的映射问题-Spring不能识别端点,除非端点以结尾/结束

时间:2019-04-15 10:53:03

标签: spring

我想首先从我刚接触Spring的信息开始。因此,在过去的几天里,这种情况一直困扰着我: 鉴于我们有一个:

@RestController
public class ChildController {

    private ChildService childService;

    public ChildController(ChildService childService) {
        this.childService = childService;
    }

    @GetMapping("/children")
    public List<ChildDto> getChildren() {
        ....          
    }

    @GetMapping("/children/{id}")
    public ChildDto getChild(@PathVariable int id) {
      ...
    }

    @PostMapping("/children")
    public ChildDto addChild(@RequestBody ChildDto childDto) {
     ...
    }

    @PutMapping("/children/{id}")
    public ChildDto updateChild(@PathVariable int id, @RequestBody ChildDto childDto) {
     ...
    }

    @DeleteMapping("/children/{id}")
    public void deleteChild(@PathVariable int id) {
      ...
    }

在...的后面,存在服务的标准操作以及REST控制器对DTO对象的转换。问题是当我开始测试GET“ / children”和POST“ / children”时-当我执行以下操作时:

given(childService.getChildren())
                .willReturn(listOf(
                        new Child(1, "John", 4),
                        new Child(2, "Jill", 5)
                ));

        mockMvc.perform(MockMvcRequestBuilders.get("/children"))
                .andExpect(statusIsOK())
                .andExpect(jsonArrayPath(0, "name").value("John"))
                .andExpect(jsonArrayPath(0, "age").value(4))
                .andExpect(jsonArrayPath(1, "name").value("Jill"))
                .andExpect(jsonArrayPath(1, "age").value(5));

given(childService.addChild(new Child("::childName::", 4))).willReturn(
                new Child(1, "::childName::", 4));

        mockMvc.perform(post("/children")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonContent(new ChildDto("::childName::", 4))))
                .andExpect(statusIsOK())
                .andExpect(jsonPath("id").value(1))
                .andExpect(jsonPath("name").value("::childName::"))
                .andExpect(jsonPath("age").value(4));

获取和发布的测试不会通过(我猜Spring不能正确路由它们),除非我像这样在末尾添加斜杠

...
 mockMvc.perform(post("/children/")
...

其他的还可以。

在部署的服务器上,端点按预期方式工作,当我在末尾添加此神秘的尾部斜杠时,端点也确实匹配。

有人可以任命我朝哪个方向去检查为什么会这样,或者可能的解决方法是什么?抱歉,这是很明显的事情。预先感谢!

PS我有一个带有一些辅助方法的辅助类,例如statusIsOk(),jsonArrayPath(),jsonContent()

0 个答案:

没有答案