junit5 入门系列教程-05-junit5 断言(assert)

目录

Assert

JUnit Jupiter附带了许多JUnit 4拥有的断言方法,并添加了一些可以很好地用于Java 8 lambdas的断言方法。
所有JUnit木星断言都是 org.junit.jupiter.api.Assertions 中的静态方法断言类。

实例

  • AssertTest.java
import org.junit.jupiter.api.Test;

import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class AssertTest {

    @Test
    void standardAssertions() {
        assertEquals(2, 2);
        assertEquals(4, 4, "The optional assertion message is now the last parameter.");
        assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- "
                + "to avoid constructing complex messages unnecessarily.");
    }

    @Test
    void groupedAssertions() {
        // In a grouped assertion all assertions are executed, and any
        // failures will be reported together.
        Person person = new Person().getDefaultPerson();
        assertAll("person",
                () -> assertEquals("John", person.getFirstName()),
                () -> assertEquals("Doe", person.getLastName())
        );
    }

    @Test
    void dependentAssertions() {
        // Within a code block, if an assertion fails the
        // subsequent code in the same block will be skipped.
        Person person = new Person().getDefaultPerson();
        assertAll("properties",
                () -> {
                    String firstName = person.getFirstName();
                    assertNotNull(firstName);

                    // Executed only if the previous assertion is valid.
                    assertAll("first name",
                            () -> assertTrue(firstName.startsWith("J")),
                            () -> assertTrue(firstName.endsWith("n"))
                    );
                },
                () -> {
                    // Grouped assertion, so processed independently
                    // of results of first name assertions.
                    String lastName = person.getLastName();
                    assertNotNull(lastName);

                    // Executed only if the previous assertion is valid.
                    assertAll("last name",
                            () -> assertTrue(lastName.startsWith("D")),
                            () -> assertTrue(lastName.endsWith("e"))
                    );
                }
        );
    }

    @Test
    void exceptionTesting() {
        Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
            throw new IllegalArgumentException("a message");
        });
        assertEquals("a message", exception.getMessage());
    }

    @Test
    void timeoutNotExceeded() {
        // The following assertion succeeds.
        assertTimeout(ofMinutes(2), () -> {
            // Perform task that takes less than 2 minutes.
        });
    }

    @Test
    void timeoutNotExceededWithResult() {
        // The following assertion succeeds, and returns the supplied object.
        String actualResult = assertTimeout(ofMinutes(2), () -> {
            return "a result";
        });
        assertEquals("a result", actualResult);
    }

    @Test
    void timeoutNotExceededWithMethod() {
        // The following assertion invokes a method reference and returns an object.
        String actualGreeting = assertTimeout(ofMinutes(2), AssertTest::greeting);
        assertEquals("Hello, World!", actualGreeting);
    }

    @Test
    void timeoutExceeded() {
        // The following assertion fails with an error message similar to:
        // execution exceeded timeout of 10 ms by 91 ms
        assertTimeout(ofMillis(10), () -> {
            // Simulate task that takes more than 10 ms.
            Thread.sleep(100);
        });
    }

    @Test
    void timeoutExceededWithPreemptiveTermination() {
        // The following assertion fails with an error message similar to:
        // execution timed out after 10 ms
        assertTimeoutPreemptively(ofMillis(10), () -> {
            // Simulate task that takes more than 10 ms.
            Thread.sleep(100);
        });
    }

    private static String greeting() {
        return "Hello, World!";
    }

    private class Person {
        private String firstName;
        private String lastName;

        public Person() {
        }

        public Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public Person getDefaultPerson() {
            return new Person("ryo", "12222");
        }
    }
}

三方 jar

尽管JUnit Jupiter提供的断言功能对于许多测试场景来说已经足够了,但是有时需要更多的功能和额外的功能,比如matchers。在这种情况下,JUnit团队推荐使用诸如AssertJ、Hamcrest、Truth等第三方断言库。因此,开发人员可以自由使用他们选择的断言库。

例如,可以使用matchers和fluent API的组合使断言更具描述性和可读性。然而, JUnit Jupiter 的 org.junit.jupiter.api.Assertions 断言类不提供类似于JUnit 4的org.junit中的assertThat()方法。
接受Hamcrest编码器的断言类。相反,鼓励开发人员使用第三方断言库提供的对匹配器的内置支持。

下面的示例演示如何在JUnit Jupiter测试中使用来自Hamcrest的assertThat()支持。
只要将Hamcrest库添加到类路径中,您就可以静态地导入诸如assertThat()、is()和equalTo()等方法,然后在像assertWithHamcrestMatcher()方法的测试中使用它们。

  • HamcrestAssertionDemo.java

当然,基于JUnit 4编程模型的遗留测试可以继续使用org.junit.Assert#assertThat。

如下:

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        assertThat(2 + 1, is(equalTo(3)));
    }

}

系列导航

系列导航

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JUnit 是一个 Java 编程语言的单元测试框架,它提供了一个注重测试驱动的开发方法,有助于在开发过程中提高代码质量、加快开发速度,并且有助于进行代码重构。JUnit 可以很容易地与持续集成工具(如 Jenkins)和构建工具(如 Maven 和 Gradle)集成使用。 下面是 JUnit 的入门使用教程: 1. 添加 JUnit 依赖库:在 Maven 或 Gradle 项目中,需要在 `pom.xml` 或 `build.gradle` 文件中添加 JUnit 依赖库。 Maven 示例: ```xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> ``` Gradle 示例: ```groovy testImplementation 'junit:junit:4.13.2' ``` 2. 创建测试类:在 Java 项目中,需要创建一个测试类,并使用 `@Test` 注解标注测试方法。 ```java import org.junit.Test; public class MyClassTest { @Test public void testMyMethod() { // 测试代码 } } ``` 3. 运行测试:在 IDE 中,可以右键单击测试类或测试方法,选择“运行测试”或“调试测试”来运行测试。也可以在命令行中使用 Maven 或 Gradle 命令来运行测试。 Maven 示例: ``` mvn test ``` Gradle 示例: ``` ./gradlew test ``` 4. 断言测试结果:可以使用 JUnit 提供的断言方法来判断测试结果是否符合预期。如果测试结果与预期不符,测试将失败并显示错误信息。 ```java import static org.junit.Assert.assertEquals; public class MyClassTest { @Test public void testMyMethod() { MyClass myClass = new MyClass(); assertEquals(10, myClass.myMethod(5, 2)); } } ``` 上述代码中使用了 JUnit 提供的 `assertEquals` 方法,它比较两个值是否相等。如果两个值相等,测试通过;否则,测试失败并显示错误信息。 这就是 JUnit 的入门使用教程。除了 `@Test` 注解和断言方法外,JUnit 还提供了许多其他注解和功能,如 `@Before` 和 `@After` 注解、`@RunWith` 注解、参数化测试、异常测试等。可以去官网或其他教程了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值