【问题标题】:Spring Boot Web Test - 404 Not foundSpring Boot Web 测试 - 404 未找到
【发布时间】:2018-05-31 19:50:20
【问题描述】:

我正在尝试使用 @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]]

【问题讨论】:

  • 我在没有SecurityConfig 的情况下运行了您的代码并且它工作正常,我认为您的SecurityConfig 没有正确加载并停止从单元测试方法中访问控制器。
  • 在我的安全配置中,我已为此目的允许所有 URL。如果我更改此设置,例如保护此 URL,则错误为 401(未授权),这没关系。

标签: spring spring-mvc spring-boot testing


【解决方案1】:

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

显然,以下是不够的。

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

你需要做的,

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

【讨论】:

    【解决方案2】:

    我可以尝试更改注释

    @WebMvcTest(RegistroClienteController.class)

    到

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

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 2019-01-20
      • 1970-01-01
      • 2019-11-09
      • 2015-05-09
      • 2019-09-16
      • 1970-01-01
      • 2018-09-23
      • 2017-09-06
      相关资源
      最近更新 更多