spring mock使用纯代码

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 必要加这个不然无法使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值