我尝试创建我的第一个测试,一个简单的 spring 启动控制器,但我得到 Handler: Type = null
. 在浏览器代码中工作但测试失败 . 我的应用程序使用spring-security . 请帮我解决一个问题并理解我的错误 . 谢谢 .
这是控制器:
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方法= GET请求URI = / get_all_items参数= {} Headers = {Accept = [text / html]}处理程序:Type = null异步:Async started = false异步结果= null已解决异常:Type = null ModelAndView: View name = null View = null Model = null FlashMap:Attributes = null MockHttpServletResponse:Status = 403错误消息=拒绝访问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]}内容类型= null正文=转发的URL = null重定向的URL = null Cookies = [] java.lang.AssertionError:状态预期:200实际:403
1 回答
这本质上是一个重复的问题,已在此处得到解答:https://stackoverflow.com/a/38676144/388980
解决方案是为您的Spring Security配置导入
@Configuration
类,除了声明@WebMvcTest(ItemController.class)
之类的@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