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

相关推荐
Json____2 小时前
从零构建家政服务平台:一套全栈架构如何打通管理端与移动端-java-springboot
java·spring boot·后端·架构·毕设·wwwoop.com
abcyuu3 小时前
福州中小企业业财一体化系统权限管理与数据安全实践方案
大数据·网络·数据库
云雀衔光3 小时前
Java Spring AI MCP:在 Spring 里把 AI 接上你的业务系统
java·开发语言·人工智能·后端·测试工具·spring
重生之小比特3 小时前
【Java SE】数据类型与变量
java·开发语言·python
苏渡苇3 小时前
Spring Insight 里如何对 Span 进行清洗
java·spring boot·后端·spring·系统监控
find1star3 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
Yeniden3 小时前
Java 后端从零到企业级:第1篇 Java 基础语法——变量、数据类型与运算符
java·开发语言·apache
邪修king3 小时前
Linux系统篇(二十三) 基础 IO:从“文件”到“文件描述符”,彻底理解重定向
android·java·linux
云雀衔光3 小时前
MCP + 应用生成:让 AI 直接产出可交互的应用
java·人工智能·测试工具·microsoft·交互·ai编程
灵境(虚幻知音)3 小时前
效能评估指标体系构建:方法、流程与模板
android·数据库