2016-07-30 74 views
5

我试图测试@WebMvcTestSecurityConfig类中定义自定义安全设置:测试安全1.4

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN"); 
    } 
} 

测试类:

@RunWith(SpringRunner.class) 
@WebMvcTest(value = ExampleController.class) 
public class ExampleControllerMockMVCTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @Test 
    public void indexTest() throws Exception { 
     mockMvc.perform(get("/")) 
     .andExpect(status().isOk()) 
     .andExpect(view().name("index")); 
    } 

    @Test 
    public void adminTestWithoutAuthentication() throws Exception { 
     mockMvc.perform(get("/admin")) 
     .andExpect(status().is3xxRedirection()); //login form redirect 
    } 

    @Test 
    @WithMockUser(username="example", password="password", roles={"ANONYMOUS"}) 
    public void adminTestWithBadAuthentication() throws Exception { 
     mockMvc.perform(get("/admin")) 
     .andExpect(status().isForbidden()); 
    } 

    @Test 
    @WithMockUser(username="user", password="password", roles={"ADMIN"}) 
    public void adminTestWithAuthentication() throws Exception { 
     mockMvc.perform(get("/admin")) 
     .andExpect(status().isOk()) 
     .andExpect(view().name("admin")) 
     .andExpect(model().attributeExists("name")) 
     .andExpect(model().attribute("name", is("user"))); 
    } 
} 

测试失败,因为他们使用的是Spring Boot的默认安全设置。

我可以使用@SpringBootTest + @AutoConfigureMockMvc修复此问题,但是如果不运行所有自动配置,测试会很有趣。

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = WebEnvironment.MOCK) 
@AutoConfigureMockMvc 
public class ExampleControllerSpringBootTest { 

    @Autowired 
    private MockMvc mockMvc; 

    // tests 
} 

有没有什么办法,@WebMvcTest可以使用SecurityConfig类中定义的设置?

+0

只需将其添加到“application.properties”(位于“src/main/resources”)中:security.user.password = password(并选择您自己的密码) –

+1

谢谢,但不修复它...仍然使用默认安全设置但将密码强制为“密码”。我只是使用角色“ADMIN”保护“/ admin *”URI,默认安全配置使用角色“USER”保护所有URI。 – dmunozfer

+0

感谢您的评论大卫。我没有意识到默认安全保护所有的URI都是用'USER'。 – Snekse

回答

7

WebMvcTest只会加载您的控制器,没有别的(这就是为什么我们称之为切片)。我们无法弄清楚你需要哪部分配置,哪一部分不需要。如果安全配置不在您的主要@SpringBootApplication上,您必须明确导入它。否则,Spring Boot将启用默认安全设置。

如果您使用的是类似OAuth的东西,那是件好事,因为您真的不想开始将它用于模拟测试。如果您将@Import(SecurityConfig.class)添加到您的测试中,会发生什么情况?

+1

仅供参考:在Spring Boot问题跟踪器中也有相关的讨论:https://github.com/spring-projects/spring-boot/issues/6514 –