我尝试为一个简单的 spring-boot Controller 创建我的第一个测试,但我得到了 Handler: Type = null
。在浏览器中,代码可以工作,但测试失败。我的应用程序使用 spring-security。请帮我解决一个问题并理解我的错误。谢谢。
这是 Controller :
private final ItemService service;
@GetMapping("/get_all_items")
public String getAllItems(Model model) {
model.addAttribute("items", service.getAll());
return "all_items";
}
这是一个测试。
@RunWith(SpringRunner.class)
@WebMvcTest(ItemController.class)
public class ItemControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private ItemService itemService;
@Test
@WithMockUser(username = "user", roles = "user")//mock security.
public void whenGetAllItemsThenControllerReturnAllItems() throws Exception {
given(
itemService.getAll()
).willReturn(
new ArrayList<Item>()
);
mvc.perform(
get("/get_all_items").accept(MediaType.TEXT_HTML)
).andExpect(
status().isOk()
);
}
}
这是结果日志:
MockHttpServletRequest: HTTP Method = GET Request URI = /get_all_items Parameters = {} Headers = {Accept=[text/html]}
Handler: Type = null
Async: Async started = false Async result = null
Resolved Exception: Type = null
ModelAndView: View name = null View = null Model = null
FlashMap: Attributes = null
MockHttpServletResponse: Status = 403 Error message = Access is denied 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], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []
java.lang.AssertionError: Status Expected :200 Actual :403
最佳答案
这本质上是一个已在此处回答的重复问题:https://stackoverflow.com/a/38676144/388980
除了声明 @WebMvcTest(ItemController.class)
之外,解决方案是为您的 Spring Security 配置导入 @Configuration
类此 @Import(SecurityConfig.class)
(假设您的 Spring Security 自定义配置位于名为 SecurityConfig
的类中)。
您可能还会发现 Spring Boot 问题跟踪器中的讨论也很有帮助:https://github.com/spring-projects/spring-boot/issues/6514
另一种选择是禁用 Spring Security,如下所述:Disable security for unit tests with spring boot
关于java - 为什么 Spring 测试失败,不起作用@MockBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45905591/