文章目录
一般使用的常见的单元测试工具是: JUnit,Mockito,AssertJ
一、引入相关的maven依赖
JUnit
JUnit是最常用的Java单元测试框架之一,提供了丰富的API来编写和组织测试用例。
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.9.1</version><scope>test</scope></dependency>
Mockito
用于模拟各个外部接口或者属性方法的数据
<dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>4.8.1</version><scope>test</scope></dependency>
AssertJ
提供了丰富的断言库,使得断言更加简洁和易读。
<dependency><groupId>org.assertj</groupId><artifactId>assertj-core</artifactId><version>3.24.2</version><scope>test</scope></dependency>
二. 常见模拟用法
1. 静态类
使用MockedStatic @Cleanup注解自动close
@CleanupMockedStatic<URLDecoder> urlDecoderMockedStatic =Mockito.mockStatic(URLDecoder.class);
urlDecoderMockedStatic.when(()->URLDecoder.decode(Mockito.any(),Mockito.anyString())).thenReturn(JSONUtil.toJsonStr(depositTradeResp));
2. 工具类
使用mockConstruction
Mockito.mockConstruction(AesUtil.class,(util,context)->Mockito.when(util.decryptMsg(Mockito.anyString())).thenReturn(true));
3. 私有方法
使用反射机制
Method checkCouponByQuery = createGoOrderService.getClass().getDeclaredMethod("checkCouponByQuery",List.class,List.class,List.class);
checkCouponByQuery.setAccessible(true);try{
checkCouponByQuery.invoke(createGoOrderService, addedXPlusOrderInfoList, usableCoupon, checkCouponResultList);}catch(Exception e){
logger.info("异常信息:{}", e.getMessage());}
3. 局部模拟
ReflectUtil.setFieldValue(changeOrderService,"changeInfoMapper", changeInfoMapperOne);BDDMockito.when(changeInfoMapperOne.getSubSegOrderList()).thenReturn(Arrays.asList("sdsd","sds"));
三. 单测类实现
BaseTest 工具类
packagecom.csair.ecs;importorg.junit.After;importorg.junit.Before;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.ActiveProfiles;importorg.springframework.test.context.junit4.SpringRunner;importorg.springframework.test.context.web.WebAppConfiguration;importorg.springframework.test.web.servlet.MockMvc;importorg.springframework.test.web.servlet.setup.MockMvcBuilders;importorg.springframework.web.context.WebApplicationContext;importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;@RunWith(SpringRunner.class)@WebAppConfiguration@SpringBootTest(
classes =GroupNeedServiceApplication.class)publicclassBaseTest{publicstaticfinalStringUTF_8="UTF-8";@AutowiredprivateWebApplicationContext webAppConfiguration;privateMockMvc mockMvc;/**
* 读取json字符串
*/privateString paramJsonStr;/**
* 提供子类进行调用,获取自己需要的参数 通过Thread的classLoader进行获取当前classPath的数据
*
* @param classPathJsonFileName
* testResources中的文件名称.
*/publicvoidloadJsonParam(String classPathJsonFileName){StringBuilder sb =newStringBuilder(300);try(BufferedInputStream inputStream =newBufferedInputStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(classPathJsonFileName));BufferedReader reader =newBufferedReader(newInputStreamReader(inputStream,UTF_8));){String temp;while((temp = reader.readLine())!=null){
sb.append(temp);}}catch(IOException e){
e.printStackTrace();}this.paramJsonStr = sb.toString();}/**
* 测试准备操作.准备好mockMvc环境
*/@Beforepublicvoidinit(){
mockMvc =MockMvcBuilders.webAppContextSetup(webAppConfiguration).build();}/**
* 测试扫尾操作
*/@Afterpublicvoidafter(){}publicMockMvcgetMockMvc(){return mockMvc;}publicStringgetParamJsonStr(){return paramJsonStr;}}
测试类
@Slf4jpublicclassSystemParamsConfigServiceImplTestextendsBaseTest{@AutowiredprivateSystemParamsConfigService systemParamsConfigService;@SneakyThrows@TestpublicvoidtestSelectParamsPageList(){{finalSystemParamsConfigReq req =newSystemParamsConfigReq();
req.getPage().setPageNo(1);
req.getPage().setPageSize(5);finalResponseBase<PageData<SystemParamsConfig>> responseBase = systemParamsConfigService.selectParamsPageList(req);// Verify the results
log.info("结果"+JSONUtil.parseObj(responseBase));}{finalSystemParamsConfigReq req =newSystemParamsConfigReq();
req.getPage().setPageNo(1);
req.getPage().setPageSize(5);
req.setParamKey("dd");finalResponseBase<PageData<SystemParamsConfig>> responseBase = systemParamsConfigService.selectParamsPageList(req);// Verify the results
log.info("结果"+JSONUtil.parseObj(responseBase));}{finalSystemParamsConfigReq req =newSystemParamsConfigReq();
req.getPage().setPageNo(1);
req.getPage().setPageSize(5);
req.setRemark("d");finalResponseBase<PageData<SystemParamsConfig>> responseBase = systemParamsConfigService.selectParamsPageList(req);// Verify the results
log.info("结果 =====> "+JSONUtil.parseObj(responseBase));}}@SneakyThrows@TestpublicvoidtestGetByParamKey(){finalResponseBase<SystemParamsConfig> responseBase = systemParamsConfigService.getByParamKey("aa");// Verify the results
log.info(" 结果 =====> "+JSONUtil.parseObj(responseBase));}@SneakyThrows@TestpublicvoidtestInsertParamConfig(){finalSystemParamsConfig paramsConfig =newSystemParamsConfig();
paramsConfig.setParamKey(RandomUtil.randomNumbers(6));
paramsConfig.setParamValue("测试");
paramsConfig.setOperator("测试人员");
paramsConfig.setRemark("备注备注");{finalResponseBase<Integer> responseBase = systemParamsConfigService.insertParamConfig(paramsConfig);// Verify the results
log.info(" 结果 =====> "+JSONUtil.parseObj(responseBase));setParamKey(paramsConfig.getParamKey());}{
paramsConfig.setParamKey("ferferfrefrefrefer");finalResponseBase<Integer> responseBase = systemParamsConfigService.insertParamConfig(paramsConfig);// Verify the results
log.info(" 结果 =====> "+JSONUtil.parseObj(responseBase));}}
四.idea查看覆盖率
在IntelliJ IDEA中,鼠标右键选中某个单元测试类或包,选择 更多运行/调试 - 使用覆盖率 - 使用覆盖率运行。
等待单元测试运行结束,会在IDEA右侧弹出覆盖率面板。
在代码中查看具体覆盖情况,红色为未覆盖的,绿色为覆盖的。
五.官方文档
Mockito 的官方文档提供了详细的说明和示例,帮助开发者更好地理解和使用 Mockito。以下是官方文档的链接:
Mockito
版权归原作者 曙iu 所有, 如有侵权,请联系我们删除。