4

我想知道我應該如何去驗證用戶的測試?就目前而言,我所寫的所有測試都將失敗,因爲端點需要授權。Spring Boot 1.4測試啓用了安全性?

測試代碼:

@RunWith(SpringRunner.class) 
@WebMvcTest(value = PostController.class) 
public class PostControllerTest { 

    @Autowired 
    private MockMvc mvc; 

    @MockBean 
    private PostService postService; 

    @Test 
    public void testHome() throws Exception { 
     this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("posts")); 
    } 


} 

一個解決方案,我發現是通過設置安全爲false @WebMvcTest禁用它。但那不是我想要做的。

任何想法?

回答

10

Spring Security提供一個@WithMockUser註釋,可用於指示test should be run as a particular user

@Test 
@WithMockUser(username = "test", password = "test", roles = "USER") 
public void withMockUser() throws Exception { 
    this.mockMvc.perform(get("/")).andExpect(status().isOk()); 
} 

或者,如果您正在使用基本身份驗證,您可以發送所需的Authorization頭:

@Test 
public void basicAuth() throws Exception { 
    this.mockMvc 
      .perform(get("/").header(HttpHeaders.AUTHORIZATION, 
        "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))) 
      .andExpect(status().isOk()); 
} 
+3

Spring Security甚至還內置了對[測試HTTP基本認證]的支持(http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#testing-http-basic-authentication) 。 ;) –

+0

我見過這個例子,但由於某種原因我沒有權限訪問這個註解。我錯過了什麼? – Lithicas

+7

註釋包含在_spring-security-test_中。只需將依賴項_org.springframework.security:spring-security-test_添加到您的項目中即可 –

相關問題