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

相关推荐
Warren9840 分钟前
如何在 Spring Boot 中安全读取账号密码等
java·开发语言·spring boot·后端·安全·面试·测试用例
杨杨杨大侠1 小时前
第1篇:走进日志框架的世界 - 从HelloWorld到企业级应用
java·开源·apache log4j
.Shu.1 小时前
Mysql InnoDB 底层架构设计、功能、原理、源码系列合集【五、InnoDB 高阶机制与实战调优】
数据库·mysql
David爱编程2 小时前
Java 内存模型(JMM)全景图:并发世界的底层基石
java·后端
努力努力再努力wz2 小时前
【c++进阶系列】:万字详解多态
java·linux·运维·开发语言·c++
秦亿凡2 小时前
多线程下为什么用ConcurrentHashMap而不是HashMap
java·开发语言
新法国菜3 小时前
MySql知识梳理之DDL语句
数据库·mysql
知其然亦知其所以然3 小时前
SpringAI + Groq 实战:3 分钟教你搭建超快聊天机器人!
java·后端·openai
阿波罗尼亚3 小时前
ExcelUtils实现 设置内容 插入行 复制行列格式
java·开发语言
Monkey-旭3 小时前
Android 定位技术全解析:从基础实现到精准优化
android·java·kotlin·地图·定位