问题描述
使用单元测试时,需要调用项目的其他接口,而其中有的接口涉及到了权限管理,因为不是从前端带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;
}