MockMvc单元测试的参数传递

MockMvc单元测试的参数传递

MockMvc的参数传递

简单的介绍下用法

比如要模拟前端传送过来3个参数
username
password
age

UserController添加一个用户

@Autowired
UserService userService;
public void insertUser(@RequestParam @Validated String username, String password, String age){
Integer row=userService.insert(username, password, age);
if (row>0){
System.out.println(“添加成功”);
} else {
System.out.println(“添加失败”);
}
}
这里用到了2个注解:
1、@RequestParam ( org.springframework.web.bind.annotation.RequestParam)
2、@Validated ( org.springframework.validation.annotation.Validated)
请看到最后再去百度注解

@Test
public void insertTest() throws Exception {
    String loginName = "text";
    String password= "123456";
    String age = "30";
    RequestBuilder request = MockMvcRequestBuilders.post("/user/adduser")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("loginName",loginName)
            .param("password",password)
            .param("age ",age );

    MvcResult mvcResult = mvc.perform(request).andReturn();
    int status = mvcResult.getResponse().getStatus();
    
    System.out.println("返回状态码:" + status);
}

语法:mockMvc.perform(MockMvcRequestBuilders.请求方式(“url”).contentType(MediaType.APPLICATION_FORM_URLENCODED).param(“键”,“值”);

和上面例子里的对比一下大家应该稍微明白怎么用了(还看不懂的我只能说开发不适合你)
上面这个例子是模拟表单提交的

下面再介绍一个JSON格式的,毕竟现在是一套后台,N个前端,下面例子用到了FastJson

@Test
public void insertTest() throws Exception {
	UserEntity user=new UserEntity();
    user.setLoginName("test");
    user.setPassword( "123456");
    user.setAge("30");
    String jsonStr=JSON.toJSONString(user);
    RequestBuilder request = MockMvcRequestBuilders.post("/user/adduser")
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(jsonStr);

    MvcResult mvcResult = mvc.perform(request).andReturn();
    int status = mvcResult.getResponse().getStatus();
    
    System.out.println("返回状态码:" + status);
}

你以为完了?当然没有,因为,我们要修改很多东西,UserController中方法的参数,Service层,实现类,给人的感觉就是,这不是等于没有解耦么,前后端的交互方式在项目开始就要定下来,现在前后端分离基本都是采用的json进行数据传递,所以我推荐第二种方法,无非就是多几个DTO类(啥事DTO类?不懂去百度吧)

public void insertUser(@RequestBody @Validated UserEntity user){
	Integer row=userService.insert(user);
	if (row>0){
		System.out.println("添加成功");
	} else {
		System.out.println("添加失败");
	}
}

这里将@RequestParam替换为了@RequestBody

至于注解,我就不在说了,请去百度,有详细的专门介绍的,我今天只给大家介绍介绍MockMvc的参数传递。

最后说明,只是给刚接触MockMvc的人,用最简单方式,拿来就用。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值