测试之MockMvc与Mockito

目录

MockMvc测试接口

测试类外壳

测试函数Controller内容编写

获取接口返回json

Mockito测试Service

thenReturn模拟结果

Throw模拟异常

Verify验证


MockMvc测试接口

测试类外壳

 @RunWith(SpringRunner.class)
 @SpringBootTest(classes = Application.class)
 @AutoConfigureMockMvc
 @Transactional
 @Sql(scripts = "/test.sql")
 ​
 public class ControllerTest {
 ​
     @Autowired
     MockMvc mockMvc;
     
     @Test
     public void test(){
         // do...
     }
     
 }

其中@Sql用法见测试之@Sql(自动插入sql脚本,测试后销毁)_夜落%的博客-CSDN博客

测试函数Controller内容编写

mockmvc的perform方法内编写发送请求的url、编码、内容等信息,后面的.andExpect方法则是对获取返回信息的验证判断。

 // 测试 - 未使用查询时,获取到的数据量
 mockMvc.perform(post("/list/1/10"))
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.code").value(200))
                 .andExpect(jsonPath("$.data.list").isNotEmpty())
                 .andExpect(jsonPath("$.data.list").isArray())
                 .andExpect(jsonPath("$.data.list", hasSize(3)));
                 
                 
 // 测试 - 使用查询时,查询用户12,获取到的数据
 SearchDTO search1 = SearchDTO.builder().id("12").build();
 mockMvc.perform(post("/list/1/10")
                 .contentType(MediaType.APPLICATION_JSON_UTF8)
                 .content(JSON.toJSONString(search1)))
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.code").value(200))
                 .andExpect(jsonPath("$.data.list").isNotEmpty())
                 .andExpect(jsonPath("$.data.list").isArray())
                 .andExpect(jsonPath("$.data.list", hasSize(1)))
                 .andExpect(jsonPath("$.data.list[0].name").value("张三"));

获取接口返回json

 MvcResult mvcResult = mockMvc.perform(get("/list/1")).andReturn();
 MockHttpServletResponse response = mvcResult.getResponse();
 response.setCharacterEncoding("UTF-8");
 String JsonReturn = response.getContentAsString();

json转对象

 UserEntity userEntity = new ObjectMapper().readValue(JsonReturn,UserEntity.class);

json转List

 List<UserEntity> userList = new ObjectMapper().readValue(JsonReturn,
                               new TypeReference<List<UserEntity>>(){});

Mockito测试Service

Mockito可以模拟方法的返回结果。

例:Mockito.when(A).thenReturn(B); 即模拟A方法的返回结果为B。

thenReturn模拟结果

下面代码中,在UserDao上注解@MockBean表示Mockito会帮我们模拟出一个假的UserDao对象,该对象的方法返回结果由when()、thenReturn()模拟。

 @MockBean
 UserDao userDao;
 ​
 @Autowired
 UserService userService;
 ​
 @Test 
 public void test(){
 ​
     List<UserEntity> userList = new ArrayList<>();
     userList.add(new UserEntity().setId(1L).setUsername("小夜"));
     userList.add(new UserEntity().setId(2L).setUsername("小音"));
     Mockito.when(userDao.mySelectList(12)).thenReturn(userList);
 ​
     List<UserEntity> list = userService.mySelectList(12);
     list.forEach(System.out::println);
 ​
 }

其中:userService.mySelectList()方法使用了userDao.mySelectList()方法

 @Override
 public List<UserEntity> mySelectList(int id) {
     return userDao.mySelectList(id);
 }

结果:

 UserEntity(id=1, username=小夜, password=null, name=null)
 UserEntity(id=2, username=小音, password=null, name=null)

Throw模拟异常

此外,还可以使用thenThrow模拟出现异常

 Mockito.when(userDao.mySelectList(22)).thenThrow(new RuntimeException("不能输入22"));

也可以使用doThrow模拟异常,注意此时方法要写在when外面

 Mockito.doThrow(new RuntimeException("不能输入33")).when(userDao).mySelectList(33);

Verify验证

使用times(x)验证方法最大允许运行次数为x,超出则错误。

注意是“验证”,所以该方法的编写应该在测试语句的最后,即等业务方法执行完成后,检验其执行的次数。

 Mockito.verify(userDao,Mockito.times(2)).mySelectList(44);

其中times()可以换成atLeast()、atLeastOnce()、atMost()、atMoreOnce()以及never()。

方法字面意思即其含义,不再赘述。

结合使用Assert.that()等方法验证Service返回结果即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值