spring Sping Boot MockMvc无法使用@PathVariable进行测试[重复]

7xzttuei  于 2022-12-21  发布在  Spring
关注(0)|答案(3)|浏览(127)
    • 此问题在此处已有答案**:

Why does "@PathVariable" fail to work on an interface in SpringBoot [duplicate](1个答案)
5年前关闭。
使用Spring Boot,我想测试我的@RestController,除了我尝试使用@PathParam测试请求Map时,一切都很好。
这涉及到接口(在本例中是TestController),它包含请求Map的注解!如果我删除接口,一切都很好......看起来是个问题......
我的控制者:

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 ")的情况下工作的...
如果我删除控制器的接口,它的工作...
有人能给我解释一下吗?
谢谢

3okqufwl

3okqufwl1#

这里有两种方法:
1.更改终结点的URL:

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

mockMvc.perform(get("/test")
            .param("foo", "Value"))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().string("foovalue"));

1.使用正确的URL调用端点:

mockMvc.perform(get("/user/1568/delete"))
    .andExpect(status().is2xxSuccessful())
    .andExpect(content().string("foovalue"));
bkkx9g8r

bkkx9g8r2#

你可以试试这个:

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

fwzugrvs3#

PathVariable不同于requestParam,因为pathVariable是URL的一部分。这就是为什么.param("foo", "foovalue")不会覆盖您的pathVariable,因为后者正在设置requestParam。
请参阅@请求参数与@路径变量

相关问题