junit_demo
参考:JUnit5单元测试框架的使用教程与简单实例_junit5使用_pan_junbiao的博客-CSDN博客
Junit单元测试例子demo_twentyfour4ever的博客-CSDN博客
目录结构
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion> 4.0 . 0 </modelVersion> <groupId>org.example</groupId> <artifactId>junit_demo</artifactId> <version> 1.0 -SNAPSHOT</version> <packaging>jar</packaging> <name>junit_demo</name> <url>http: //maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF- 8 </project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version> 3.8 . 1 </version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> </dependencies> </project> |
被测试类
1 2 3 4 5 6 7 8 9 10 11 | package com.hmb; public class Calculator { public int add( int a, int b) { return a + b; } public int sub( int a, int b) { return a - b; } } |
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | package com.hmb; import junit.framework.Assert; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; class CalculatorTest { static Calculator calculator; static int testNo = 0 ; @BeforeAll static void beforeAll() { System.out.println( "test start..." ); calculator = new Calculator(); } @AfterAll static void AfterAll() { System.out.println( "test end..." ); } @org .junit.jupiter.api.BeforeEach void setUp() { System.out.println( "start test NO. " + testNo); } @AfterEach void tearDown() { System.out.println( "end test NO. " + testNo++); } @org .junit.jupiter.api.Test void add() { int result = calculator.add( 1 , 2 ); Assert.assertEquals( 3 , result); } @org .junit.jupiter.api.Test void sub() { int result = calculator.sub( 2 , 1 ); Assert.assertEquals( 1 , result); } } |
运行结果:
点击测试类名左边的运行按钮,就会运行所有此类测试用例
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术