目录
JUnit5与之前版本的Junit框架有很大的不同。由三个不同子项目的几个不同模块组成。

JUnit Platform: Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
JUnit Jupiter: JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部 包含了一个测试引擎,用于在Junit Platform上运行。
JUnit Vintage: 由于JUint已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x,Junit3.x的测试引擎。
注意:
- <dependency>
- <groupId>org.junit.vintagegroupId>
- <artifactId>junit-vintage-engineartifactId>
- <scope>testscope>
- <exclusions>
- <exclusion>
- <groupId>org.hamcrestgroupId>
- <artifactId>hamcrest-coreartifactId>
- exclusion>
- exclusions>
- dependency>
引入Junit5:
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
测试:
- @SpringBootTest
- class testJunit5{
-
- @Test
- void testHello() {
-
- }
- }
断言(assertions)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。检查业务逻辑返回的数据是否合理。所有的测试运行结束以后,会有一个详细的测试报告;
用来对单个值进行简单的验证
| 方法 | 说明 |
| assertEquals | 判断两个对象或两个原始类型是否相等 |
| assertNotEquals | 判断两个对象或两个原始类型是否不相等 |
| assertSame | 判断两个对象引用是否指向同一个对象 |
| assertNotSame | 判断两个对象引用是否指向不同的对象 |
| assertTrue | 判断给定的布尔值是否为 true |
| assertFalse | 判断给定的布尔值是否为 false |
| assertNull | 判断给定的对象引用是否为 null |
| assertNotNull | 判断给定的对象引用是否不为 null |
方法参数:
测试值
期望值
测试值与期望值不符时打印的信息
通过 assertArrayEquals 方法来判断两个对象或原始类型的数组是否相等
- @Test
- @DisplayName("array assertion")
- public void array() {
- assertArrayEquals(new int[]{1, 2}, new int[] {1, 2});
- }
assertAll 方法接受多个 org.junit.jupiter.api.Executable 函数式接口的实例作为要验证的断言,可以通过 lambda 表达式很容易的提供这些断言
- @Test
- @DisplayName("assert all")
- public void all() {
- assertAll("Math",
- () -> assertEquals(2, 1 + 1),
- () -> assertTrue(1 > 0)
- );
- }
- @Test
- @DisplayName("异常测试")
- public void exceptionTest() {
- ArithmeticException exception = Assertions.assertThrows(
- //扔出断言异常
- ArithmeticException.class, () -> System.out.println(1 % 0));
-
- }
Assertions.assertTimeout() 为测试方法设置了超时时间
- @Test
- @DisplayName("超时测试")
- public void timeoutTest() {
- //如果测试方法时间超过1s将会异常
- Assertions.assertTimeout(Duration.ofMillis(1000), () -> Thread.sleep(500));
- }
前置条件(assumptions【假设】)类似于断言,不同之处在于不满足的断言会使得测试方法失败,而不满足的前置条件只会使得测试方法的执行终止。前置条件可以看成是测试方法执行的前提,当该前提不满足时,就没有继续执行的必要。
assumeTrue 和 assumFalse 确保给定的条件为 true 或 false,不满足条件会使得测试执行终止。
assumingThat 的参数是表示条件的布尔值和对应的 Executable 接口的实现对象。只有条件满足时,Executable 对象才会被执行;当条件不满足时,测试执行并不会终止。
- @DisplayName("前置条件")
- public class AssumptionsTest {
- private final String environment = "DEV";
-
- @Test
- @DisplayName("simple")
- public void simpleAssume() {
- assumeTrue(Objects.equals(this.environment, "DEV"));
- assumeFalse(() -> Objects.equals(this.environment, "PROD"));
- }
-
- @Test
- @DisplayName("assume then do")
- public void assumeThenDo() {
- assumingThat(
- Objects.equals(this.environment, "DEV"),
- () -> System.out.println("In DEV")
- );
- }
- }
JUnit 5 可以通过 Java 中的内部类和@Nested 注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起。在内部类中可以使用@BeforeEach 和@AfterEach 注解,而且嵌套的层次没有限制。对于before/after只对于同层或者更里层的测试有效,对于外层不生效。
- @DisplayName("A stack")
- class TestingAStackDemo {
-
- Stack
-
- @Test
- @DisplayName("is instantiated with new Stack()")
- void isInstantiatedWithNew() {
- new Stack<>();
- }
-
- @Nested
- @DisplayName("when new")
- class WhenNew {
-
- @BeforeEach
- void createNewStack() {
- stack = new Stack<>();
- }
-
- @Test
- @DisplayName("is empty")
- void isEmpty() {
- assertTrue(stack.isEmpty());
- }
-
- @Test
- @DisplayName("throws EmptyStackException when popped")
- void throwsExceptionWhenPopped() {
- assertThrows(EmptyStackException.class, stack::pop);
- }
-
- @Test
- @DisplayName("throws EmptyStackException when peeked")
- void throwsExceptionWhenPeeked() {
- assertThrows(EmptyStackException.class, stack::peek);
- }
-
- @Nested
- @DisplayName("after pushing an element")
- class AfterPushing {
-
- String anElement = "an element";
-
- @BeforeEach
- void pushAnElement() {
- stack.push(anElement);
- }
-
- @Test
- @DisplayName("it is no longer empty")
- void isNotEmpty() {
- assertFalse(stack.isEmpty());
- }
-
- @Test
- @DisplayName("returns the element when popped and is empty")
- void returnElementWhenPopped() {
- assertEquals(anElement, stack.pop());
- assertTrue(stack.isEmpty());
- }
-
- @Test
- @DisplayName("returns the element when peeked but remains not empty")
- void returnElementWhenPeeked() {
- assertEquals(anElement, stack.peek());
- assertFalse(stack.isEmpty());
- }
- }
- }
- }
利用@ValueSource等注解,指定入参,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。
@ValueSource: 为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型
@NullSource: 表示为参数化测试提供一个null的入参
@EnumSource: 表示为参数化测试提供一个枚举入参
@CsvFileSource:表示读取指定CSV文件内容作为参数化测试入参
@MethodSource:表示读取指定方法的返回值作为参数化测试入参(注意方法返回需要是一个流)
- @ParameterizedTest
- @ValueSource(strings = {"one", "two", "three"})
- @DisplayName("参数化测试1")
- public void parameterizedTest1(String string) {
- System.out.println(string);
- Assertions.assertTrue(StringUtils.isNotBlank(string));
- }
-
-
- @ParameterizedTest
- @MethodSource("method") //指定方法名
- @DisplayName("方法来源参数")
- public void testWithExplicitLocalMethodSource(String name) {
- System.out.println(name);
- Assertions.assertNotNull(name);
- }
-
- static Stream
method() { - return Stream.of("apple", "banana");
- }
当然如果参数化测试仅仅只能做到指定普通的入参还达不到让我觉得惊艳的地步。让我真正感到他的强大之处的地方在于他可以支持外部的各类入参。如:CSV,YML,JSON 文件甚至方法的返回值也可以作为入参。只需要去实现ArgumentsProvider接口,任何外部文件都可以作为它的入参。