Spring Boot Web Test - 404未找到

时间:2018-05-31 19:50:20

标签: spring spring-mvc spring-boot testing

我正在尝试使用@WebMvcTest测试一个非常简单的GET请求的控制器,但是我得到的是404而不是200,并且控制台没有给我任何有用的东西来理解发生了什么。

我在控制器的开头放了一个断点但它永远不会到达。如果我运行应用程序,端点将按预期工作。

这是我的控制器:

@RestController
public class RegistroClienteController  {        

    @GetMapping("/api/registro-cliente")
    public ResponseEntity<Void> crearCliente() {
        return new ResponseEntity<Void>(HttpStatus.OK);
    }
}

这是我的测试:

@RunWith(SpringRunner.class)
@WebMvcTest(RegistroClienteController.class)
@ContextConfiguration(classes = { SecurityConfig.class })
public class RegistroClienteControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    UserDetailsService userDetailsService;

    @Test
    public void test() throws Exception {
        //@formatter:off
        mockMvc
            .perform(get("/api/registro-cliente"))
            .andExpect(status().isOk());
        //@formatter:on
    }
}

和控制台的输出:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/registro-cliente
       Parameters = {}
          Headers = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = [[Cookie@624b3544 name = 'XSRF-TOKEN', value = 'f9d63654-4e21-4d41-b3bb-6767703268b5', comment = [null], domain = [null], maxAge = -1, path = '/', secure = false, version = 0, httpOnly = false]]

2 个答案:

答案 0 :(得分:1)

我可以尝试更改注释

@WebMvcTest(RegistroClienteController.class)

@SpringBootTest(classes = {your application class}.class)

答案 1 :(得分:0)

我遇到了相同的错误,经过数小时的搜索,发现该错误是由于未注册控制器引起的。问题描述here

显然,以下内容还不够。

@WebMvcTest(controllers = {<ControllerToTest>.class})

您需要做

@WebMvcTest(controllers = {<ControllerToTest>.class})
@Import(<ControllerToTest.class>)