关于junit测试与spring security时

问题描述
使用单元测试时,需要调用项目的其他接口,而其中有的接口涉及到了权限管理,因为不是从前端带token发过来的 所以会出现一些问题(比如 直接从容器中获取当前用户会报空

解决方法:
1.

1.在测试类上加 前两个注解
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc //非必须 其他测试需要
public class DataCollectionTest {
    @Autowired
    DataCollectionController dataCollectionController;
    @Autowired
    UploadPartService uploadPartService;
    @Autowired
    AuthService authService;
    @Mock
    AuthController authController;
    @Mock
    MockMvc mockMvc;

    SecurityContext context;

    Authentication authentication;

    Principal principal;
    @Autowired
    JwtTokenService jwtTokenService;

2.
//在@Before可以在执行目标方法前  往容器中加入一些你需要的对象
@Before
public void init(){
        LoginDTO loginDTO = LoginDTO.builder().password("e10adc3949ba59abbe56e057f20f883e").userEmailNum("260241").sign(1).build(); // 我的登录类 这个根据你自己实际情况构建你的登录参数
        String token = authService.loginByPassword(loginDTO);  //处理登录请求返回token的方法  调你自己的
        JWTUser jwtUser = jwtTokenService.validateToken(token); //拿到JWTUser 这里也调你自己的
//        MockitoAnnotations.initMocks(this);

        context = SecurityContextHolder.getContext();// 拿到容器对象
        authentication = jwtTokenService.getAuthentication(token,jwtUser);
        SecurityContextHolder.getContext().setAuthentication(authentication);//往里面设置值即可
//        SecurityContextHolder.setContext(this.context);
    }
//使用mock模拟http请求

   ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders
                    .post("/dataCollection/add")//请求方式  路径
                    .content(JSONObject.toJSONString(dataCollectionResultDTO)) //请求体
                    .accept(MediaType.APPLICATION_JSON) 
                    .contentType(MediaType.APPLICATION_JSON_TYPE.getType())
                    .header("Authorization", "Bearer " + s) //请求头设置参数

//这是我封装的一个方法
//requestBody  后台使用@requestBody 注解接收参数时使用  否则为null
//token  登陆后返回的token
//path  请求路径
// requestType 请求类型小写 post,get等
//paramsMap 请求参数 键值对
public MockHttpServletResponse sendHttp(Object requestBody, String token, String path, String requestType, HashMap<String,String> paramsMap) throws Exception {
        MockHttpServletRequestBuilder requestBuilder = null;
        switch (requestType) {
            case "post":
                requestBuilder = MockMvcRequestBuilders.post(path);
                break;
            case "get":
                requestBuilder = MockMvcRequestBuilders.get(path);
                break;
            case "delete":
                requestBuilder = MockMvcRequestBuilders.delete(path);
                break;
            case "put":
                requestBuilder = MockMvcRequestBuilders.put(path);
                break;
            default:
                break;
        }
        if (requestBody != null){
            requestBuilder.content(JSONObject.toJSONString(requestBody))
                    .contentType(MediaType.APPLICATION_JSON_TYPE.getType());
        }
        if (paramsMap.size()!=0){
            Set<Entry<String, String>> entries = paramsMap.entrySet();
            for(Map.Entry<String,String> entry : entries){
                String key = entry.getKey();
                String value = entry.getValue();
                requestBuilder.param(key,value);
            }
        }
        ResultActions resultActions = mockMvc.perform(requestBuilder
                .header("Authorization", "Bearer " + token)
                .header("Connection","keep-alive")
                .accept(MediaType.APPLICATION_JSON) //设置请求返回值类型

        );
        MockHttpServletResponse response = resultActions.andReturn().getResponse();
        response.setCharacterEncoding("utf-8");
        return response;
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
```xml <!-- Spring Boot Starter Parent --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Thymeleaf Spring Security --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency> <!-- Spring Boot Starter Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> ``` 注释说明: 1. Spring Boot Starter Parent:Spring Boot 的父级依赖,定义了 Spring Boot 的版本和依赖管理。 2. Spring Boot Starter WebSpring Boot Web 组件的依赖,包含了 Spring MVC、Tomcat 等。 3. Spring SecuritySpring Security 组件的依赖,提供了安全认证和授权功能。 4. Thymeleaf:Thymeleaf 模板引擎的依赖,用于生成 HTML 页面。 5. Thymeleaf Spring Security:Thymeleaf 和 Spring Security 集成的依赖,提供了 Thymeleaf 中使用 Spring Security 的标签和属性。 6. Spring Boot Starter Test:Spring Boot 测试组件的依赖,包含了 JUnit、Mockito 等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值