我需要使用Spring Security测试我们的REST控制器.我正在使用MockMvc作为弹簧安全参考建议
http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test-mockmvc
测试:
@ContextConfiguration(locations = "classpath:applicationContext.xml") @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration public class LikesTest { protected MockMvc mockMvc; @Autowired private WebApplicationContext context; @Before public void setup() { mockMvc = MockMvcBuilders .webAppContextSetup(context) //.standaloneSetup(new MessageController()) .apply(SecurityMockMvcConfigurers.springSecurity()) .build(); } @Test @WithMockUser("user") public void testAddLike() throws Exception { mockMvc.perform(get("/like?msgId=4&like=false")); } }
当我正在运行JUnit测试时,我正在获得此故障跟踪
org.springframework.security.web.FilterChainProxy.getFilters(FilterChainProxy.java:223)中的java.lang.NullPointerException
另外如果删除applicationContext.xml中的bean:
然后我得到了这个失败的痕迹:
java.lang.IllegalStateException:springSecurityFilterChain不能为null.确保使用名称为springSecurityFilterChain的Bean实现Filter,或者注入要使用的Filter.在org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurer.beforeMockMvcCreated(SecurityMockMvcConfigurer.java:62)
我不知道为什么FilterChainProxy为null.在我的Web.xml中,我已经使用filter-name springSecurityFilterChain声明了DelegatingFilterProxy,我的应用程序运行正常.请帮我!谢谢