相关疑难解决方法(0)

使用Spring Security进行Spring MVC集成测试

我正在尝试使用mvc-test测试我的登录页面.在我添加spring security之前,我工作得很好.

我的代码是:

 mockMvc.perform(
     post("j_spring_security_check")
                    .param(LOGIN_FORM_USERNAME_FIELD, testUsernameValue)
                    .param(LOGIN_FORM_PASSWORD_FIELD, testPasswordValue))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(model().attribute(LOGIN_PAGE_STATUS_VALUE, LOGIN_PAGE_STATUS_FALSE_INDICATOR));
Run Code Online (Sandbox Code Playgroud)

测试类添加了正确的注释:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:security-context.xml", "classpath:applicationContext.xml", "classpath:test-contexts/test-context.xml" })
Run Code Online (Sandbox Code Playgroud)

我的过滤器已定义(在web.xml中):

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)

当我尝试在@ContextConfiguration中添加web.xml时,它会失败,当我删除它时,我得到一个例外:

java.lang.AssertionError: Status expected:<200> but was:<405>
Run Code Online (Sandbox Code Playgroud)

有没有办法添加DelegatingProxyFilter来测试上下文与我的security-context.xml中定义的配置,使其工作?我尝试了一些注入FilterProxyChain的教程,但它不适用于我的情况.

有人可以帮助我吗?提前致谢

spring-mvc spring-security spring-test-mvc

26
推荐指数
1
解决办法
3万
查看次数

Spring Boot设置安全性以进行测试

我无法在测试中正确配置安全性.我的网络安全配置:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/**").hasRole("USER")
                .and()
                .httpBasic()
        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试班:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration
@ContextConfiguration(classes = {Application.class, AppConfig.class, WebMvcConfig.class, WebSecurityConfig.class})
@WebAppConfiguration
public class TestControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = webAppContextSetup(wac).dispatchOptions(true).build();
    }

    @Test
    public void getTest() throws Exception {
        mockMvc
                .perform(get("/api/test"))
                .andExpect(status().isForbidden())
        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到404状态代码意味着没有执行安全层,因此在我的测试类中没有正确配置它.我试图将类切换@ContextConfiguration@SpringApplicationConfiguration没有成功.

java spring spring-mvc spring-boot

7
推荐指数
2
解决办法
1万
查看次数