日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
SpringSecurity實戰(zhàn)干貨:SpringSecurity中的單元測試

今天組里的新人迷茫的問我:哥,Spring Security弄的我單元測試跑不起來,總是401,你看看咋解決。沒問題,有寫單元測試的覺悟,寫的代碼質(zhì)量肯定有保證,對代碼質(zhì)量重視的態(tài)度,這種忙一定要幫!

Spring Security 測試環(huán)境

要想在單元測試中使用Spring Security,你需要在Spring Boot項目中集成:

 
 
 
  1.             org.springframework.security
  2.             spring-security-test
  3.             test
  4.         

這樣測試的上下文配置就能和Spring Security結(jié)合起來了,接下來教你幾招。

Spring Security 測試

所有的測試都是在Spring Boot Test下進行的,也就是@SpringBootTest注解的支持下。

@WithMockUser

@WithMockUser注解可以幫我們在Spring Security安全上下文中模擬一個默認名稱為user,默認密碼為password,默認角色為USER的用戶。當你的測試方法使用了該注解后,你就能通過:

 
 
 
  1. Authentication authentication = SecurityContextHolder.getContext()
  2.            .getAuthentication();

獲取該模擬用戶的信息,也就“假裝”當前登錄了用戶user。當然你也可以根據(jù)需要來自定義用戶名、密碼、角色:

 
 
 
  1. @SneakyThrows
  2. @Test
  3. @WithMockUser(username = "felord",password = "felord.cn",roles = {"ADMIN"})
  4. void updatePassword() {
  5.     mockMvc.perform(post("/user/update/password")
  6.             .contentType(MediaType.APPLICATION_JSON)
  7.             .content("{\n" +
  8.                     "  \"newPassword\": \"12345\",\n" +
  9.                     "  \"oldPassword\": \"12345\"\n" +
  10.                     "}"))
  11.             .andExpect(ResultMatcher.matchAll(status().isOk()))
  12.             .andDo(print());
  13. }

當然你可以將@WithMockUser標記到整個測試類上,這樣每個測試都將使用指定該用戶。

@WithAnonymousUser

@WithAnonymousUser是用來模擬一種特殊的用戶,也被叫做匿名用戶。如果有測試匿名用戶的需要,可以直接使用該注解。其實等同于@WithMockUser(roles = {"ANONYMOUS"}),也等同于@WithMockUser(authorities = {"ROLE_ANONYMOUS"}),細心的你應(yīng)該能看出來差別。

@WithUserDetails

雖然@WithMockUser是一種非常方便的方式,但可能并非在所有情況下都湊效。有時候你魔改了一些東西使得安全上下文的驗證機制發(fā)生了改變,比如你定制了UserDetails,這一類注解就不好用了。但是通過UserDetailsService 加載的用戶往往還是可靠的。于是@WithUserDetails就派上了用場。

 
 
 
  1. @SneakyThrows
  2. @Test
  3. @WithUserDetails("felord")
  4. void updatePassword() {
  5.     mockMvc.perform(post("/user/update/password")
  6.             .contentType(MediaType.APPLICATION_JSON)
  7.             .content("{\n" +
  8.                     "  \"newPassword\": \"12345\",\n" +
  9.                     "  \"oldPassword\": \"12345\"\n" +
  10.                     "}"))
  11.             .andExpect(ResultMatcher.matchAll(status().isOk()))
  12.             .andDo(print());
  13. }

當我們執(zhí)行單元測試時,將通過UserDetailsService 的loadUserByUsername方法查找用戶名為felord的用戶并加載到安全上下文中。

自定義注解

其實我們還可以模擬@WithMockUser

 
 
 
  1. @Target({ ElementType.METHOD, ElementType.TYPE })
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Inherited
  4. @Documented
  5. @WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
  6. public @interface WithMockUser {
  7.    String value() default "user";
  8.    String username() default "";
  9.    String[] roles() default { "USER" };
  10.  
  11.    String[] authorities() default {};
  12.  
  13.    String password() default "password";
  14.  
  15.    @AliasFor(annotation = WithSecurityContext.class)
  16.    TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
  17. }

關(guān)鍵就在于@WithSecurityContext注解,我們只需要實現(xiàn)factory就行了,也就是:

 
 
 
  1. public interface WithSecurityContextFactory {
  2.  
  3.    SecurityContext createSecurityContext(A annotation);
  4. }

這里如法炮制就行,沒什么難度就不演示了。

總結(jié)

今天介紹了當你的應(yīng)用中集成了Spring Security時如何單元測試,我們可以使用提供的模擬用戶的注解,也可以模擬加載用戶,甚至你可以根據(jù)自己的需要來定制化。其實如果你使用了JWT的話還有種野路子,你可以在Spring MVC Mock測試中加入對應(yīng)的請求頭或者參數(shù),也能順利進行。


網(wǎng)頁標題:SpringSecurity實戰(zhàn)干貨:SpringSecurity中的單元測試
文章網(wǎng)址:http://www.5511xx.com/article/djoipeh.html