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

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

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

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

我的 Controller :

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") ...时,第二个测试正在工作......

如果我删除 Controller 的接口(interface),它就可以工作......

谁能给我解释一下吗?

谢谢

最佳答案

这里有两种方法:

  1. 更改端点的 URL:

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    
    mockMvc.perform(get("/test")
                .param("foo", "Value"))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().string("foovalue"));
    
  2. 使用正确的 URL 调用您的端点:

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

关于java - Spring Boot MockMvc 无法使用 @PathVariable 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45996088/

相关文章:

java - Android:java.lang.IllegalStateException:无法执行 Activity 的方法

java - 如何使用spring向不同的web服务发送并发请求

unit-testing - 何时使用 httptest.Server 和 httptest.ResponseRecorder

python - 单元测试没有返回值的方法

java - 单击按钮后显示小窗口

java - 如何获取字符串中的单词?

java - 如何修复 java.util.concurrent.ExecutionException :

java - 用于嵌套属性的 Jackson2 PropertyFilter,还是有其他方法?

javascript - 如何将 Spring Mvc Controller 5 连接到 jsp 文件?

unit-testing - 在 Grails 3 单元测试中使用 Spock 数据驱动测试