java测试junit

JUnit Platform是底层的测试执行引擎,JUnit Jupiter是JUnit 5的主要测试框架,而JUnit Vintage允许在JUnit 5平台上运行旧版本的测试。

所以想要使用junit5,必须包含platform和jupiter。

JUnit Platform

├── JUnit Jupiter

└── JUnit Vintage

复制代码
//常用注解测试
@DisplayName("Common annotation test")
public class AnnotationsTest {

    private static Add add;

    @BeforeAll
    public static void beforeAll() {
        add=new Add();
        //在所有测试方法运行前运行
        System.out.println("Run before all test methods run");
    }

    @BeforeEach
    public void beforeEach() {
        //每个测试方法运行前运行
        System.out.println("Run before each test method runs");
    }

    @AfterEach
    public void afterEach() {
        //每个测试方法运行完毕后运行
        System.out.println("Run after each test method finishes running");
    }

    @AfterAll
    public static void afterAll() {
        //在所有测试方法运行完毕后运行
        System.out.println("Run after all test methods have finished running");
    }

    @Disabled
    @Test
    @DisplayName("Ignore the test")
    public void disabledTest() {
        //这个测试不会运行
        System.out.println("This test will not run");
    }

    @Test
    @DisplayName("Test Methods 1+1")
    public void testAdd1() {
        System.out.println("Running test method1+1");
        Assertions.assertEquals(2,add.add(1,1));
    }

    @Test
    @DisplayName("Test Methods 2+2")
    public void testAdd2() {
        System.out.println("Running test method2+2");
        Assertions.assertEquals(4,add.add(2,2));
    }


}

常用断言

assertEquals

检查两个值是否相等。

assertEquals(expected, actual);

assertNotEquals

检查两个值是否不相等。

assertNotEquals(notExpected, actual);

assertTrue 和 assertFalse

验证条件是否为真或为假。

assertTrue(condition);

assertFalse(condition);

assertNull 和 assertNotNull

验证值是否为 null 或不为 null。

assertNull(nullValue);

assertNotNull(nonNullValue);

assertArrayEquals

检查两个数组是否相等。

assertArrayEquals(expectedArray, actualArray);

assertThrows

验证是否抛出了期望的异常。

assertThrows(ExpectedException.class, () -> {

// 代码块,期望抛出 ExpectedException 异常

});

assertDoesNotThrow

验证没有抛出异常。

assertDoesNotThrow(() -> {

// 代码块,不应该抛出任何异常

});

assertSame 和 assertNotSame:

验证两个对象是否是同一个引用或不是同一个引用。

assertSame(expectedObject, actualObject);

assertNotSame(notExpectedObject, actualObject);

相关推荐
byte轻骑兵16 分钟前
时序数据库选型指南:Apache IoTDB 社区版实践与踩坑
数据库·人工智能·apache·时序数据库·iotdb
jyOverQ1 小时前
从零学 JVM(七):垃圾收集器详解——Serial、ParNew、Parallel、CMS 与 G1
java·jvm
liangbo71 小时前
Spring系列11:切点表达式
java·spring
黄连木笛1 小时前
Redis Insight 汉化教程:Windows / macOS / Linux 设置中文界面(附繁體、教程汉化、关闭自动更新)
数据库·redis·缓存
3095566661 小时前
股票接口返回 404 与空数组的排查笔记:证书状态与级别参数
java·笔记·python·ios·iphone·股票数据api·股票数据接口
nice_lcj5201 小时前
MySQL 存储引擎入门:InnoDB 和 MyISAM 到底怎么选
java·数据库·mysql·面试·innodb·存储引擎·myisam
文丑颜不良啊1 小时前
LeetCode2861~2880题目解析
java·leetcode
装不满的克莱因瓶2 小时前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式
晴天的雨.9922 小时前
【C++】继承篇
java·开发语言·c++
SomeOtherTime2 小时前
第 1 讲:内存布局与所有权解剖——栈帧、胖指针与“移动/拷贝”在汇编层面的真实面目
java·开发语言·汇编