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

相关推荐
码兄科技5 小时前
Java AI智能体开发实战:从零构建智能对话系统指南
java·开发语言·人工智能
折哥的程序人生 · 物流技术专研6 小时前
第8篇:六大设计原则在工厂模式中的体现
java·设计模式·设计原则·工厂模式·编程进阶·扩充系列
小明bishe186 小时前
计算机毕业设计之基于JAVA的植物科普网站
java·spring boot·spring·架构·课程设计
r_oo_ki_e_6 小时前
Java Map 集合学习笔记
java·笔记·学习
SL-staff7 小时前
智慧园区2000+设备统一管理:JVS-IoT如何降低运维成本40%
java·开发语言·物联网·智慧园区·设备管理·运维优化·jvs-iot
咖啡八杯7 小时前
GoF设计模式——模板方法模式
java·后端·spring·设计模式
爱笑的源码基地8 小时前
一款全开源的信创云PACS影像云平台解决方案,支持多模态医学影像处理(CT/MR/DR/超声/病理等)
java·源码·国产化·pacs·云影像·区域pacs
我命由我123458 小时前
Android 开发问题:ClickableSpan 的点击事件没有生效
java·java-ee·android studio·android jetpack·android-studio·android runtime
云和恩墨8 小时前
数据库一体机简史:从ODA到zData X,命名之中的玄机
数据库·vr
万亿少女的梦1688 小时前
基于Python的高考志愿填报辅助系统设计与实现
java·spring boot·python·mysql·vue