ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

8.3 单元测试,包括security测试

2022-07-19 06:00:38  阅读:154  来源: 互联网

标签:8.3 单元测试 content test safeBoxJson put Safebox security


创建一个Spring Boot 项目时会自动创建一个test文件夹,所有的测试都在其中进行。

依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

 

 

 如果需要测试security的话还需要添加依赖

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

 

例子

@SpringBootTest
@AutoConfigureMockMvc //该注解表示MockMvc由spring容器构建。如果不加入这个注释的话无法使用 mvc
public class SafeBoxBetaResourceTest {
    @Autowired
    protected MockMvc mvc;
    @Autowired
    protected SafeBoxService safeBoxService;


    private static JSONArray jsonArray = new JSONArray(); 
  /* json list, 如
  {
    "items": [
      "Safebox content 01",
      "Safebox content 02",
      "Safebox content 03"
    ]
  }
  */ @BeforeAll 表示应在当前测试类中的所有测试之前执行一次(就算同时运行当前测试类中的多个方法也只运行一次)注解方法
    // 注解的方法必须是静态方法,否则它将引发运行时错误 public static void setup() throws Exception { // Mock Entities jsonArray.put("Safebox content 01"); jsonArray.put("Safebox content 02"); jsonArray.put("Safebox content 03"); } // create safebox @Test
  @WithMockUser(username = "user", password = "passwod123", role = {"ADMIN"})
  // 模拟一个用户, 也就“假装”当前登录了用户
void create_safe_box_return_200() throws Exception {
        var safeBoxJson = new JSONObject();
        safeBoxJson.put("name", "Secure safebox 01");
        safeBoxJson.put("password", "extremelySecurePassword1!");
       var request = post(访问地址) // 可以是 get,put,delete .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(safeBoxJson.toString()); // request body
mvc.perform(request) .andExpect(status().isOk()) .andExpect(jsonPath("$.id").isNotEmpty()); // jsonPath("$.id") = json response 中的 id 值
}
  
}

@WithAnonymousUser是用来模拟匿名用户。等同于@WithMockUser(roles = {"ANONYMOUS"}),也等同于@WithMockUser(authorities = {"ROLE_ANONYMOUS"})

@WithUserDetails 当通过UserDetailsService 加载的用户的时候使用。@WithUserDetails("felord")当我们执行单元测试时,将通过UserDetailsService 的loadUserByUsername方法查找用户名为felord的用户

 

//

标签:8.3,单元测试,content,test,safeBoxJson,put,Safebox,security
来源: https://www.cnblogs.com/ShengLiu/p/16492636.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有