当前位置: 首页 > news >正文

java之 junit单元测试案例【经典版】

一  junit单元测试

1.1 单元测试作用

单元测试要满足AIR原则,即

A: automatic 自动化;

I: Independent  独立性;

R:Repeatable 可重复;

2.单元测试必须使用assert来验证

1.2 案例1 常规单元测试

1.代码

public class CalcDemo
{public int add(int x ,int y){return x + y;//return x * y;}public int sub(int x ,int y){return x - y;}
}

2.测试

public class AppTest {@Testvoid sub(){CalcDemo calcDemo = new CalcDemo();int retValue = calcDemo.sub(2, 2);assertEquals(0,retValue);System.out.println("");}
}

1.3 案例2 单元覆盖率Coverage*

1.代码

public class ScoreDemo
{public String scoreLevel(int score){if(score <= 0) {throw new IllegalArgumentException("缺考");} else if (score < 60) {return "弱";} else if (score < 70) {return "差";} else if (score <= 80) {return "中";} else if (score < 90) {return "良";} else {return "优";}}
}

2.测试

class ScoreDemoTest
{@Testvoid scoreLevel(){ScoreDemo scoreDemo = new ScoreDemo();assertEquals("弱",scoreDemo.scoreLevel(52));}@Testvoid scoreLevelv2(){ScoreDemo scoreDemo = new ScoreDemo();assertEquals("差",scoreDemo.scoreLevel(62));}@Testvoid scoreLevelv3(){ScoreDemo scoreDemo = new ScoreDemo();assertEquals("中",scoreDemo.scoreLevel(80));}@Testvoid scoreLevelv4(){ScoreDemo scoreDemo = new ScoreDemo();assertThrows(IllegalArgumentException.class,() -> scoreDemo.scoreLevel(-7));}
}

查看测试报告:对应覆盖率

1.4 案例3 BeforeEach,BeforeAfterall

1.代码

public class CalcDemo
{public int add(int x ,int y){return x + y;//return x * y;}public int sub(int x ,int y){return x - y;}
}

2.测试 

class CalcDemoTestV2
{CalcDemo calcDemo = null;static StringBuffer stringBuffer = null;@BeforeAllstatic void m1(){stringBuffer = new StringBuffer("abc");System.out.println("===============: "+stringBuffer.length());}@AfterAllstatic void m2(){System.out.println("===============: "+stringBuffer.append(" ,end").toString());}@BeforeEachvoid setUp(){System.out.println("----come in BeforeEach");calcDemo = new CalcDemo();}@AfterEachvoid tearDown(){System.out.println("----come in AfterEach");calcDemo = null;}@Testvoid add(){assertEquals(5,calcDemo.add(1,4));assertEquals(5,calcDemo.add(2,3));}@Testvoid sub(){assertEquals(5,calcDemo.sub(10,5));}
}

3.结果

1.5 案例4  junit+反射+注解实现测试

1.定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AtguiguTest
{
}

2.定义调用类

public class CalcHelpDemo
{public int mul(int x ,int y){return x * y;}@AtguiguTestpublic int div(int x ,int y){return x / y;}@AtguiguTestpublic void thank(int x ,int y){System.out.println("3ks,help me test bug");}
}

3.定义测试类

@Slf4j
public class AutoTestClient
{public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException{//家庭作业,抽取一个方法,(class,p....)CalcHelpDemo calcHelpDemo = new CalcHelpDemo();int para1 = 10;int para2 = 0;Method[] methods = calcHelpDemo.getClass().getMethods();AtomicInteger bugCount = new AtomicInteger();// 要写入的文件路径(如果文件不存在,会创建该文件)String filePath = "BugReport"+ (DateUtil.format(new Date(), "yyyyMMddHHmmss"))+".txt";for (int i = 0; i < methods.length; i++){if (methods[i].isAnnotationPresent(AtguiguTest.class)){try{methods[i].invoke(calcHelpDemo,para1,para2);//放行} catch (Exception e) {bugCount.getAndIncrement();log.info("异常名称:{},异常原因:{}",e.getCause().getClass().getSimpleName(),e.getCause().getMessage());FileUtil.writeString(methods[i].getName()+"\t"+"出现了异常"+"\n", filePath, "UTF-8");FileUtil.appendString("异常名称:"+e.getCause().getClass().getSimpleName()+"\n", filePath, "UTF-8");FileUtil.appendString("异常原因:"+e.getCause().getMessage()+"\n", filePath, "UTF-8");}finally {FileUtil.appendString("异常数:"+bugCount.get()+"\n", filePath, "UTF-8");}}}}
}

4.查看结果

1.6 案例5  web工程单元测试

1.pom配置

   <!--test--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--test--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

2.处理类

@Service
public class MemberService
{public String add(Integer uid){System.out.println("---come in addUser,your uid is: "+uid);if (uid == -1){throw new IllegalArgumentException("parameter is negative。。。。");}return "ok";}public int del(Integer uid){System.out.println("---come in del,your uid is: "+uid);return uid;}
}

3.启动类

@SpringBootApplication
public class App 
{public static void main( String[] args ){SpringApplication.run(App.class, args);System.out.println( "Hello World!" );}
}

4.测试类

@SpringBootTest
public class MemberTest {@Resource //真实调用,落盘mysql-MQ=redis。。。。测试条件充分的情况下private MemberService memberService1;//    @Test
//    void m1()
//    {
//        String result = memberService1.add(2);
//        assertEquals("ok",result);
//
//        System.out.println("----m1 over");
//    }@MockBeanprivate MemberService memberService2;//    @Test
//    void m2_NotMockRule()
//    {
//        String result = memberService2.add(2);
//        assertEquals("ok",result);
//
//        System.out.println("----m2_NotMockRule over");
//    }//    @Test
//    void m2_WithMockRule()
//    {
//        when(memberService2.add(3)).thenReturn("ok");//不真的进入数据库/MQ,不落盘,改变return
//
//        String result = memberService2.add(3);
//        assertEquals("ok",result);
//
//        System.out.println("----m2_WithMockRule over");
//    }
@SpyBean //有规则按照规则走,没有规则走真实
private MemberService memberService3;@Testvoid m3(){when(memberService3.add(2)).thenReturn("ok");String result = memberService3.add(2);System.out.println("----add result:  "+result);Assertions.assertEquals("ok",result);int result2 = memberService3.del(3);System.out.println("----del result2:  "+result2);Assertions.assertEquals(3,result2);//跨部门调用,不是写代码,累的是心,协调工作。    zzyybs@126.comSystem.out.println("----over");}
}

4.结果

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 在 CentOS-Stream-9 中使用 network 代替 NetworkManager
  • Apache AGE的MATCH子句
  • 增量预训练和微调的区别
  • Python 读取esxi上所有主机的设备信息
  • Keka for Mac v1.4.3 中文下载 解压/压缩工具
  • 【Arduino IDE】安装及开发环境、ESP32库
  • PF4J+SpringBoot
  • Vscode中Github copilot插件无法使用(出现感叹号)解决方案
  • Vite的WebSocket
  • python的tkinter、socket库开发tcp的客户端和服务端
  • 智慧博物馆的“眼睛”:视频智能监控技术守护文物安全与智能化管理
  • 详细解析Kafaka Streams中各个DSL操作符的用法
  • Hive第三天
  • 单例模式 饿汉式和懒汉式的区别
  • 推荐一款处理TCP数据的架构--EasyTcp4Net
  • 【Linux系统编程】快速查找errno错误码信息
  • Angular2开发踩坑系列-生产环境编译
  • angular学习第一篇-----环境搭建
  • Docker入门(二) - Dockerfile
  • ERLANG 网工修炼笔记 ---- UDP
  • java架构面试锦集:开源框架+并发+数据结构+大企必备面试题
  • Laravel Telescope:优雅的应用调试工具
  • LeetCode算法系列_0891_子序列宽度之和
  • MobX
  • Spring Cloud(3) - 服务治理: Spring Cloud Eureka
  • vue从入门到进阶:计算属性computed与侦听器watch(三)
  • XML已死 ?
  • 订阅Forge Viewer所有的事件
  • 搞机器学习要哪些技能
  • 力扣(LeetCode)357
  • 猫头鹰的深夜翻译:JDK9 NotNullOrElse方法
  • 入门到放弃node系列之Hello Word篇
  • 使用iElevator.js模拟segmentfault的文章标题导航
  • 微信开放平台全网发布【失败】的几点排查方法
  • 异常机制详解
  • HanLP分词命名实体提取详解
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • #我与Java虚拟机的故事#连载08:书读百遍其义自见
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (Python) SOAP Web Service (HTTP POST)
  • (超详细)语音信号处理之特征提取
  • (附源码)spring boot基于Java的电影院售票与管理系统毕业设计 011449
  • (附源码)springboot青少年公共卫生教育平台 毕业设计 643214
  • (蓝桥杯每日一题)平方末尾及补充(常用的字符串函数功能)
  • (十五)使用Nexus创建Maven私服
  • (一)appium-desktop定位元素原理
  • (转)JAVA中的堆栈
  • .NET C# 操作Neo4j图数据库
  • .net core 6 集成 elasticsearch 并 使用分词器
  • .NET 分布式技术比较
  • .NET 给NuGet包添加Readme
  • .NET 使用 JustAssembly 比较两个不同版本程序集的 API 变化
  • .net6 core Worker Service项目,使用Exchange Web Services (EWS) 分页获取电子邮件收件箱列表,邮件信息字段
  • .NET6 命令行启动及发布单个Exe文件
  • .NET是什么