简体   繁体   English

Spring MVC RestController 测试未能找到有效的映射

[英]Spring MVC RestController test failed to find valid mapping

I failed to test RestController method with path variable我无法使用路径变量测试 RestController 方法

INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/my/{env}] onto handler 'myController'
INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/my/{env}.*] onto handler 'myController'
INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/my/{env}/] onto handler 'myController'
INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 205 ms
WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/my/dev/auth] in DispatcherServlet with name ''

My Test我的测试

@ContextConfiguration( classes = {Config.class, MyController.class})
@ActiveProfiles(profiles= {"dev"})
@WebAppConfiguration
public class MyControllerTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;


    @BeforeClass
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testAuth() throws Exception {
        MockHttpSession httpSession =  new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());
        MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders
        .post("/my/dev/auth").content("<XML></XML>")
        .session(httpSession)
        .contentType(MediaType.APPLICATION_XML);
         MvcResult mvcResult = this.mockMvc.perform(mockHttpServletRequestBuilder)
                  .andDo(MockMvcResultHandlers.print())
                  .andReturn(); 

My Controller我的控制器

@RestController
@RequestMapping(value = "/my/{env}")
public class MyController {

@PostMapping(value = "auth", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody ResponseEntity<Response> authenticate(
            @PathVariable("env") String gameEnvironment, @RequestBody String xml,
            HttpServletRequest httpRequest) {

EDIT编辑

Removing path variable result in similar results删除路径变量会导致类似的结果

[main] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/my] onto handler 'myController'
[main] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/my.*] onto handler 'myController'
[main] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/my/] onto handler 'myController'
[main] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/my/auth] in DispatcherServlet with name ''

The following works with JUnit 4.以下适用于 JUnit 4。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Config.class, MyController.class })
@ActiveProfiles("dev")
@WebAppConfiguration("classpath:META-INF/web-resources")
public class MyControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;


    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testAuth() throws Exception {
        MockHttpSession httpSession = new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());

        this.mockMvc.perform(
                post("/my/dev/auth")
                    .content("<XML></XML>")
                    .session(httpSession)
                    .contentType(MediaType.APPLICATION_XML))
            .andDo(print())
            .andExpect(status().isOk());
    }

}

@Configuration
@EnableWebMvc
class Config {
}

@RestController
@RequestMapping("/my/{env}")
class MyController {

    @PostMapping(path = "auth", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public String authenticate(@PathVariable("env") String env, @RequestBody String xml,
            HttpServletRequest httpRequest) {

        return null;
    }
}

And the following works with TestNG.以下适用于 TestNG。

@ContextConfiguration(classes = { Config.class, MyController.class })
@ActiveProfiles("dev")
@WebAppConfiguration("classpath:META-INF/web-resources")
public class MyControllerTestNG extends AbstractTestNGSpringContextTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;


    @BeforeClass
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testAuth() throws Exception {
        MockHttpSession httpSession = new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());

        this.mockMvc.perform(
                post("/my/dev/auth")
                    .content("<XML></XML>")
                    .session(httpSession)
                    .contentType(MediaType.APPLICATION_XML))
            .andDo(print())
            .andExpect(status().isOk());
    }

}

Test was missing classes for full loading of relevant configuration测试缺少完整加载相关配置的类

@ContextConfiguration( classes = {Config.class, MyController.class
    ,OtherConfig.class})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM