【发布时间】: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