我尝试为一个简单的 spring-boot 控制器创建我的第一个测试,但我得到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()
);
}
}
这是结果日志:
模拟HttpServlet请求:
HTTP 方法 = GET
请求 URI = /get_all_items
参数 = {}
标题 = {接受=[text/html]}
处理程序:
类型=空
异步:
异步开始 = false
异步结果 = null
已解决的异常:
类型=空
模型和视图:
视图名称=空
视图=空
型号 = 空
闪图:
属性=空
模拟HttpServlet响应:
状态 = 403
错误消息 = 访问被拒绝
标头 = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1;模式=块],缓存控制=[无缓存,无存储,
max-age=0,必须重新验证],Pragma=[无缓存],Expires=[0],
X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ;
包含子域]}
内容类型=空
身体=
转发的 URL = null 重定向的 URL = null
饼干=[]
java.lang.AssertionError:预期状态:200 实际:403
这本质上是一个重复的问题,已在这里得到回答:https://stackoverflow.com/a/38676144/388980 https://stackoverflow.com/a/38676144/388980
解决办法是import the @Configuration
除了声明之外,您的 Spring Security 配置的类@WebMvcTest(ItemController.class)
像这样@Import(SecurityConfig.class)
(假设您的 Spring Security 自定义配置位于名为SecurityConfig
).
您可能还会发现 Spring Boot 问题跟踪器中的讨论也很有帮助:https://github.com/spring-projects/spring-boot/issues/6514 https://github.com/spring-projects/spring-boot/issues/6514
另一种选择是disableSpring Security 的解释如下:使用 Spring Boot 禁用单元测试的安全性 https://stackoverflow.com/questions/31169720/disable-security-for-unit-tests-with-spring-boot/35192495
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)