Junit5 详解
简述
junit5是当前java比较流行的单元测试框架。
junit5官网:https://junit.org/junit5/
官方文档:https://junit.org/junit5/docs/current/user-guide/
中文翻译版:https://doczhcn.gitbook.io/junit5/
Junit5的构成
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。
JUnit Vintage: 由于JUint已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x,Junit3.x的测试引擎。
导入junit5依赖
gradle方式:
testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
最简单的测试案例
在方法上标注@Test注解,这个方法就是一个测试,测试方法内可以使用断言达到我们的测试效果
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class FirstJUnit5Tests { @Test void myFirstTest() { assertEquals(2, 1 + 1); } }
常用注解
全部注解:https://doczhcn.gitbook.io/junit5/index/index-2/annotations
标准测试类
import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class StandardTests { @BeforeAll static void initAll() { } @BeforeEach void init() { } @Test void succeedingTest() { } @Test void failingTest() { fail("a failing test"); } @Test @Disabled("for demonstration purposes") void skippedTest() { // not executed } @AfterEach void tearDown() { } @AfterAll static void tearDownAll() { } }
断言
断言用于比较我们期望的结果和程序实际运行的结果
References
https://juejin.cn/search?query=junit5%E8%AF%A6%E8%A7%A3&type=0
https://doczhcn.gitbook.io/junit5/
https://blog.csdn.net/chenjxj123/article/details/124366094
https://doczhcn.gitbook.io/junit5
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix