Spring Boot MockMvc无法使用@PathVariable进行测试

时间:2017-09-01 08:26:51

标签: java spring unit-testing spring-mvc spring-boot

使用Spring Boot,我想测试我的@RestController,一切都很好,除非我尝试使用@PathParam测试请求映射。

这涉及保存请求映射注释的接口(在本例中为TestController)!如果我删除界面一切都很好......似乎是一个问题...

我的控制器:

public interface TestController {

    @RequestMapping(value = "/bar/{foo}/baz", method = RequestMethod.GET)
    String test(@PathVariable("foo") String foo);


    @RestController
    class TestControllerImpl implements TestController {

        @Override
        public String test(String foo) {
            return foo;
        }
    }

}

我的测试:

@Test
public void notworkingtest() throws Exception {

    //THIS TEST SHOULD WORK, BUT DON'T ...

    final MockMvc mockMvc = ...

    mockMvc.perform(get("/bar/{foo}/baz", "foovalue") // Or get("/bar/foovalue/baz")
            .contentType("text/plain"))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().string("foovalue"));

}

@Test
public void strangeworkingtest() throws Exception {

    //THIS TEST WORKS, BUT WHY ?!?

    final MockMvc mockMvc = ...

    mockMvc.perform(get("/bar/{foo}/baz", "WhatEverValue")
            .param("foo", "foovalue") // This param should be useless ...
            .contentType("text/plain"))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().string("foovalue"));

}

当我有.param(" foo"," foovalue)时,第二个测试正在工作,并保持get(" / bar / {foo} / baz", " WhatEverValue")......

如果我删除控制器的接口,它可以工作......

有人可以向我解释一下吗?

THX

3 个答案:

答案 0 :(得分:0)

你可以试试这个:

mockMvc.perform(get("/test/{foo}?foo=" + "foovalue")
        .contentType("text/plain"))
        .andExpect(status().is2xxSuccessful())
        .andExpect(content().string("foovalue"));

答案 1 :(得分:0)

这有两种方式:

  1. 更改终端的网址:

    @RequestMapping(value =" / test",method = RequestMethod.GET)

    mockMvc.perform(得到(" /测试&#34)             .param(" foo","价值"))             .andExpect(状态()。is2xxSuccessful())             (含量()的字符串(" foovalue&#34)); .andExpect

  2. 使用正确的URL来呼叫您的终端:

    mockMvc.perform(get(" / user / 1568 / delete"))             .andExpect(状态()。is2xxSuccessful())             (含量()的字符串(" foovalue&#34)); .andExpect

答案 2 :(得分:0)

PathVariable与requestParam不同,因为pathVariable是URL的一部分。 这就是为什么.param("foo", "foovalue")没有覆盖你的pathVariable,因为后者正在设置requestParam。

请参阅@RequestParam vs @PathVariable

相关问题