spring security + spring mock使用纯代码
运行环境:springboot + spring security
用spring mock写了一个测试controller层post接口的方法
@WithMockUser因为spring security底层会进行认证,所以需要模拟认证
/**
* post接口验证,参数方式为json
* @param mockMvc
* @param data 传递的json对象
* @param url URL路径
*/
@WithMockUser(username = "#{Constant.USER}",password = "#{Constant.PASSWORD}",roles = {"#{Constant.ROLES}"})
public String postHttpParamJson(MockMvc mockMvc,Object data,String url,String accessToken) throws Exception{
String requestJson = JSONObject.toJSONString(data);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post(url)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
//请求头
.header("User-Agent",Constant.USER_AGENT)
//token
.header("Authorization",accessToken)
.content(requestJson)
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
//转码,接口返回乱码转成utf-8
content =new String(content.getBytes("ISO-8859-1"),"UTF-8");
return content;
}
具体调用上面的方法
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AdminApplication.class)
@WebAppConfiguration
@AutoConfigureMockMvc
public class InfoFileTest {
@Autowired
private WebApplicationContext context;
@Autowired
private MockMvc mockMvc;
@Before()
public void setup () {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
// 添加spring-security的验证
.apply(springSecurity())
.build();
}
@Test
public void test1() throws Exception {
MockHttpUtils mockHttpUtils = new MockHttpUtils();
//传参以对象方式传参
Param param = new Param();
param.setId("1");
param.setName("xaiom");
//controller测试路径
String url = "/api/files";
//accessToken token
mockHttpUtils.postHttpParamJson(mockMvc,fileInfoParam,url,accessToken);
}
// 添加spring-security的验证
.apply(springSecurity())
如果权限使用spring security 必要加这个不然无法使用