2016-07-30 75 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 –