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);

相关推荐
ok!ko2 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
2402_857589362 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰3 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
vvvae12343 小时前
分布式数据库
数据库
哎呦没3 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
雪域迷影4 小时前
PostgreSQL Docker Error – 5432: 地址已被占用
数据库·docker·postgresql
编程、小哥哥4 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
bug菌¹4 小时前
滚雪球学Oracle[4.2讲]:PL/SQL基础语法
数据库·oracle
逸巽散人5 小时前
SQL基础教程
数据库·sql·oracle
IT学长编程5 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统