java单元测试:JUnit断言库

JUnit断言库提供了一组用于验证测试结果的工具。这些断言方法帮助开发人员在单元测试中明确表达预期结果,并在实际结果与预期结果不符时报告失败。

1. JUnit中的断言

断言用于验证测试的预期结果。JUnit 5(Jupiter)提供了一组静态方法,可以方便地进行各种类型的断言。

常用断言方法
  • assertEquals(expected, actual):断言两个值相等。
  • assertNotEquals(expected, actual):断言两个值不相等。
  • assertTrue(condition):断言条件为真。
  • assertFalse(condition):断言条件为假。
  • assertNull(value):断言对象为null。
  • assertNotNull(value):断言对象不为null。
  • assertArrayEquals(expectedArray, actualArray):断言两个数组相等。
  • assertThrows(expectedType, executable):断言执行代码块时抛出了预期的异常。
  • assertTimeout(duration, executable):断言执行代码块在指定时间内完成。
  • assertAll(executables...):组合多个断言,确保所有断言都执行并报告所有失败。

2. 示例代码

2.1 基本断言示例
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class BasicAssertionsTest {

    @Test
    void testEquals() {
        assertEquals(5, 2 + 3, "2 + 3 should equal 5");
    }

    @Test
    void testNotEquals() {
        assertNotEquals(5, 2 + 2, "2 + 2 should not equal 5");
    }

    @Test
    void testTrue() {
        assertTrue(3 > 2, "3 should be greater than 2");
    }

    @Test
    void testFalse() {
        assertFalse(2 > 3, "2 should not be greater than 3");
    }

    @Test
    void testNull() {
        Object obj = null;
        assertNull(obj, "Object should be null");
    }

    @Test
    void testNotNull() {
        Object obj = new Object();
        assertNotNull(obj, "Object should not be null");
    }
}
2.2 数组断言示例
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class ArrayAssertionsTest {

    @Test
    void testArrayEquals() {
        int[] expected = {1, 2, 3};
        int[] actual = {1, 2, 3};
        assertArrayEquals(expected, actual, "Arrays should be equal");
    }
}
2.3 异常断言示例
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class ExceptionAssertionsTest {

    @Test
    void testThrows() {
        assertThrows(ArithmeticException.class, () -> {
            int result = 1 / 0;
        }, "Division by zero should throw ArithmeticException");
    }
}
2.4 超时断言示例
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.time.Duration;

class TimeoutAssertionsTest {

    @Test
    void testTimeout() {
        assertTimeout(Duration.ofMillis(100), () -> {
            Thread.sleep(50);
        }, "Execution should complete within 100 milliseconds");
    }
}
2.5 组合断言示例
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CombinedAssertionsTest {

    @Test
    void testAll() {
        assertAll("Multiple assertions",
            () -> assertEquals(4, 2 * 2, "2 * 2 should equal 4"),
            () -> assertTrue(3 > 2, "3 should be greater than 2"),
            () -> assertNotNull(new Object(), "Object should not be null")
        );
    }
}

3. 自定义错误消息

每个断言方法都可以接受一个可选的错误消息参数,当断言失败时会显示该消息。这有助于快速定位问题。

示例:自定义错误消息
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CustomMessageTest {

    @Test
    void testWithCustomMessage() {
        int expected = 5;
        int actual = 2 + 3;
        assertEquals(expected, actual, "2 + 3 should equal 5, but got " + actual);
    }
}

4. 高级断言技巧

4.1 组合断言

使用assertAll可以在一个测试方法中组合多个断言,确保所有断言都被执行并报告所有失败。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class MultipleAssertionsTest {

    @Test
    void testMultipleAssertions() {
        assertAll("Multiple assertions",
            () -> assertEquals(4, 2 * 2, "2 * 2 should equal 4"),
            () -> assertTrue(3 > 2, "3 should be greater than 2"),
            () -> assertNotNull(new Object(), "Object should not be null")
        );
    }
}
4.2 条件断言

使用assumeTrueassumeFalse可以在特定条件下跳过测试。这对于依赖于特定环境或配置的测试非常有用。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assumptions.*;

class AssumptionsTest {

    @Test
    void testOnlyOnCiServer() {
        assumeTrue("CI".equals(System.getenv("ENV")), "Test only runs on CI server");
        // 测试代码
    }

    @Test
    void testInAllEnvironments() {
        // 测试代码
        assertEquals(2, 1 + 1);
    }
}

总结

JUnit的断言库提供了丰富的断言方法,帮助开发者验证测试结果并确保代码的正确性。通过使用这些断言方法,可以编写清晰、简洁且有效的单元测试,从而提高代码的质量和稳定性。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AssertJ 是 JAVA 的流畅断言。示例代码:// unique entry point to get access to all assertThat methods and utility methods (e.g. entry) import static org.assertj.core.api.Assertions.*;  // common assertions assertThat(frodo.getName()).isEqualTo("Frodo"); assertThat(frodo).isNotEqualTo(sauron)                  .isIn(fellowshipOfTheRing);  // String specific assertions assertThat(frodo.getName()).startsWith("Fro")                            .endsWith("do")                            .isEqualToIgnoringCase("frodo");  // collection specific assertions assertThat(fellowshipOfTheRing).hasSize(9)                                .contains(frodo, sam)                                .doesNotContain(sauron);  // using extracting magical feature to check fellowshipOfTheRing characters name :) assertThat(fellowshipOfTheRing).extracting("name").contains("Boromir", "Gandalf", "Frodo", "Legolas")                                                   .doesNotContain("Sauron", "Elrond");  // map specific assertions, ringBearers initialized with the elves rings and the one ring bearers. assertThat(ringBearers).hasSize(4)                        .contains(entry(oneRing, frodo), entry(nenya, galadriel))                        .doesNotContainEntry(oneRing, aragorn);  // and many more assertions : dates, file, numbers, exceptions ... 标签:AssertJ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值