当前位置:   article > 正文

SpringBoot——单元测试之JUnit5_springboot junit5

springboot junit5

文章目录:

1.JUnit5的变化

2.JUnit5常用注解及测试

2.1 @DisplayName、@Disabled、@BeforeEach、@AfterEach、@BeforeAll、@AfterAll

2.2 @Timeout

2.3 @RepeatedTest

3.断言

3.1 简单断言

3.2 数组断言

3.3 组合断言

3.4 异常断言

3.5 超时断言

3.6 快速失败

4.前置条件

5.嵌套测试

6.参数化测试

7.JUnit4 → Junit5


1.JUnit5的变化

Spring Boot 2.2.0 版本开始引入 JUnit 5 作为单元测试默认库

作为最新版本的JUnit框架,JUnit5与之前版本的Junit框架有很大的不同。由三个不同子项目的几个不同模块组成。

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

JUnit Platform: Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。

JUnit Jupiter: JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部 包含了一个测试引擎,用于在Junit Platform上运行。

JUnit Vintage: 由于JUint已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x,Junit3.x的测试引擎。

注意:SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖。如果需要兼容junit4需要自行引入(不能使用junit4的功能 @Test

JUnit 5’s Vintage Engine Removed from spring-boot-starter-test,如果需要继续兼容junit4需要自行引入vintage

  1. <dependency>
  2. <groupId>org.junit.vintage</groupId>
  3. <artifactId>junit-vintage-engine</artifactId>
  4. <scope>test</scope>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>org.hamcrest</groupId>
  8. <artifactId>hamcrest-core</artifactId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>

如果只使用JUnit5的特性,那么就需要添加下面的依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>
  1. import org.junit.jupiter.api.Test;
  2. import org.springframework.boot.test.context.SpringBootTest;
  3. @SpringBootTest
  4. class SpringbootActuatorApplicationTests {
  5. @Test
  6. void contextLoads() {
  7. }
  8. }

2.JUnit5常用注解及测试

JUnit5的注解与JUnit4的注解有所变化

JUnit 5 User Guide

  • @Test :表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
  • @ParameterizedTest :表示方法是参数化测试,下方会有详细介绍
  • @RepeatedTest :表示方法可重复执行,下方会有详细介绍
  • @DisplayName :为测试类或者测试方法设置展示名称
  • @BeforeEach :表示在每个单元测试之前执行
  • @AfterEach :表示在每个单元测试之后执行
  • @BeforeAll :表示在所有单元测试之前执行
  • @AfterAll :表示在所有单元测试之后执行
  • @Tag :表示单元测试类别,类似于JUnit4中的@Categories
  • @Disabled :表示测试类或测试方法不执行,类似于JUnit4中的@Ignore
  • @Timeout :表示测试方法运行如果超过了指定时间将会返回错误
  • @ExtendWith :为测试类或测试方法提供扩展类引用

2.1 @DisplayName、@Disabled、@BeforeEach、@AfterEach、@BeforeAll、@AfterAll

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. //----------------------------常用注解----------------------------
  13. @DisplayName("测试DisplayName注解---方法1")
  14. @Test
  15. public void testDisplayName1() {
  16. System.out.println(123);
  17. }
  18. @Disabled
  19. @DisplayName("测试DisplayName注解---方法2")
  20. @Test
  21. public void testDisplayName2() {
  22. System.out.println(456);
  23. }
  24. @BeforeEach
  25. public void testBeforeEach() {
  26. System.out.println("测试就要开始了....");
  27. }
  28. @AfterEach
  29. public void testAfterEach() {
  30. System.out.println("测试已经结束了....");
  31. }
  32. @BeforeAll
  33. public static void testBeforeAll() {
  34. System.out.println("所有测试就要开始了....");
  35. }
  36. @AfterAll
  37. public static void testAfterAll() {
  38. System.out.println("所有测试已经结束了....");
  39. }
  40. }

我们再把 testDisplayName2 方法上的@Disabled注解打开。可以看到,这个测试方法已经被禁用了。

2.2 @Timeout

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. @DisplayName("测试Timeout注解")
  29. @Timeout(value = 5, unit = TimeUnit.MILLISECONDS)
  30. @Test
  31. public void testTimeout() throws InterruptedException {
  32. Thread.sleep(1000);
  33. }
  34. }

2.3 @RepeatedTest

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. @RepeatedTest(5)
  29. @Test
  30. public void testRepeatedTest() {
  31. System.out.println(1);
  32. }
  33. }


3.断言

断言(assertions)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。JUnit 5 内置的断言可以分成如下几个类别:

检查业务逻辑返回的数据是否合理。

所有的测试运行结束以后,会有一个详细的测试报告;

3.1 简单断言

用来对单个值进行简单的验证。如:

方法

说明

assertEquals

判断两个对象或两个原始类型是否相等

assertNotEquals

判断两个对象或两个原始类型是否不相等

assertSame

判断两个对象引用是否指向同一个对象

assertNotSame

判断两个对象引用是否指向不同的对象

assertTrue

判断给定的布尔值是否为 true

assertFalse

判断给定的布尔值是否为 false

assertNull

判断给定的对象引用是否为 null

assertNotNull

判断给定的对象引用是否不为 null

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. //----------------------------断言----------------------------
  29. /**
  30. * 如果前面的断言失败,则后面的代码不会再执行
  31. */
  32. @DisplayName("测试简单断言")
  33. @Test
  34. public void testSimpleAssertions() {
  35. int result = cal(1,2);
  36. assertEquals(5,result,"业务逻辑计算结果出错....");
  37. Object obj1 = new Object();
  38. Object obj2 = new Object();
  39. assertSame(obj1,obj2);
  40. }
  41. public int cal(int x, int y) {
  42. return x + y;
  43. }
  44. }

assertEquals方法判断出运算结果不同,也即此时第一个断言失败了,那么后面的assertSame不会再执行。

当我们修改assertEquals方法使其断言成功,那么后续的assertSame将会继续执行。

此时看到的就是assertSame方法打印的异常信息(两个对象不相等)。

assertEquals(3,result,"业务逻辑计算结果出错....");

3.2 数组断言

通过 assertArrayEquals 方法来判断两个对象或原始类型的数组是否相等。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. //----------------------------断言----------------------------
  29. @DisplayName("测试数组断言1")
  30. @Test
  31. public void testArrayAssertions1() {
  32. assertArrayEquals(new int[]{1,2}, new int[]{1,2});
  33. }
  34. @DisplayName("测试数组断言2")
  35. @Test
  36. public void testArrayAssertions2() {
  37. assertArrayEquals(new int[]{3,4}, new int[]{1,2}, "数组内容不相等....");
  38. }
  39. }

3.3 组合断言

assertAll 方法接受多个 org.junit.jupiter.api.Executable 函数式接口的实例作为要验证的断言,可以通过 lambda 表达式很容易的提供这些断言。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. //----------------------------断言----------------------------
  29. @DisplayName(("测试组合断言"))
  30. @Test
  31. public void testAllAssertions() {
  32. assertAll("testAll",
  33. () -> assertTrue(true && true),
  34. () -> assertEquals(1,2));
  35. //当以上两个断言全部成功时,才会打印下面的内容
  36. System.out.println("success!!!");
  37. }
  38. }

组合断言中,当所有断言都成功时,代码才会顺利向下执行。assertTrue虽然执行成功了,但是assertEquals失败了,所有下面的sout不会执行。

3.4 异常断言

在JUnit4时期,想要测试方法的异常情况时,需要用@Rule注解的ExpectedException变量还是比较麻烦的。而JUnit5提供了一种新的断言方式Assertions.assertThrows() ,配合函数式编程就可以进行使用。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. //----------------------------断言----------------------------
  29. @DisplayName("测试异常断言")
  30. @Test
  31. public void testExceptionAssertions() {
  32. assertThrows(ArithmeticException.class,() -> {
  33. int i = 10 / 2; //此时断言会执行
  34. //int j = 10 / 0; //此时断言不会执行
  35. },"业务逻辑居然正常运行???");
  36. }
  37. }

如果代码执行 int i = 10 / 2 运行正确,不会出现 ArithmeticException 异常,所以此时assertThrows断言会执行。反之则不会执行。

3.5 超时断言

Junit5还提供了Assertions.assertTimeout() 为测试方法设置了超时时间。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. @DisplayName("测试超时断言")
  29. @Test
  30. public void testTimeoutAssertions() {
  31. assertTimeout(Duration.ofMillis(1000), () -> Thread.sleep(2000));
  32. }
  33. }

3.6 快速失败

通过 fail 方法直接使得测试失败。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. @DisplayName("快速失败")
  29. @Test
  30. public void testFailAssertions() {
  31. System.out.println(1);
  32. System.out.println(2);
  33. fail("直接走人....");
  34. System.out.println(3);
  35. System.out.println(4);
  36. }
  37. }


4.前置条件

JUnit 5 中的前置条件(assumptions【假设】)类似于断言,不同之处在于不满足的断言会使得测试方法失败,而不满足的前置条件只会使得测试方法的执行终止。前置条件可以看成是测试方法执行的前提,当该前提不满足时,就没有继续执行的必要。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.*;
  3. import java.time.Duration;
  4. import java.util.concurrent.TimeUnit;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. *
  8. */
  9. //@SpringBootTest
  10. @DisplayName("Junit5功能测试类")
  11. public class TestJunit {
  12. @BeforeEach
  13. public void testBeforeEach() {
  14. System.out.println("测试就要开始了....");
  15. }
  16. @AfterEach
  17. public void testAfterEach() {
  18. System.out.println("测试已经结束了....");
  19. }
  20. @BeforeAll
  21. public static void testBeforeAll() {
  22. System.out.println("所有测试就要开始了....");
  23. }
  24. @AfterAll
  25. public static void testAfterAll() {
  26. System.out.println("所有测试已经结束了....");
  27. }
  28. //----------------------------前置条件----------------------------
  29. @DisplayName("测试前置条件")
  30. @Test
  31. public void testAssumptions() {
  32. Assumptions.assumeTrue(true, "结果不是true....");
  33. System.out.println(111);
  34. }
  35. }

将 Assumptions.assumeTrue(false, "结果不是true...."); 中的 true 改为 false,此时因为 true != false,所以不满足该前置条件,则直接导致测试方法被终止执行。


5.嵌套测试

JUnit 5 可以通过 Java 中的内部类和@Nested 注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起。在内部类中可以使用@BeforeEach 和@AfterEach 注解,而且嵌套的层次没有限制。

  1. package com.szh.boot;
  2. import org.junit.jupiter.api.BeforeEach;
  3. import org.junit.jupiter.api.DisplayName;
  4. import org.junit.jupiter.api.Nested;
  5. import org.junit.jupiter.api.Test;
  6. import java.util.EmptyStackException;
  7. import java.util.Stack;
  8. import static org.junit.jupiter.api.Assertions.*;
  9. /**
  10. * 嵌套测试中,外层的@Test不能驱动内层的@Before(After)Each/All之类的方法提前/之后运行
  11. * 内层的@Test可以驱动外层的@Before(After)Each/All之类的方法提前/之后运行
  12. */
  13. @DisplayName("A stack")
  14. public class TestingAStackDemo {
  15. Stack<Object> stack;
  16. @Test
  17. @DisplayName("is instantiated with new Stack()")
  18. void isInstantiatedWithNew() {
  19. new Stack<>();
  20. }
  21. @Nested
  22. @DisplayName("when new")
  23. class WhenNew {
  24. @BeforeEach
  25. void createNewStack() {
  26. stack = new Stack<>();
  27. }
  28. @Test
  29. @DisplayName("is empty")
  30. void isEmpty() {
  31. assertTrue(stack.isEmpty());
  32. }
  33. @Test
  34. @DisplayName("throws EmptyStackException when popped")
  35. void throwsExceptionWhenPopped() {
  36. assertThrows(EmptyStackException.class, stack::pop);
  37. }
  38. @Test
  39. @DisplayName("throws EmptyStackException when peeked")
  40. void throwsExceptionWhenPeeked() {
  41. assertThrows(EmptyStackException.class, stack::peek);
  42. }
  43. @Nested
  44. @DisplayName("after pushing an element")
  45. class AfterPushing {
  46. String anElement = "an element";
  47. @BeforeEach
  48. void pushAnElement() {
  49. stack.push(anElement);
  50. }
  51. @Test
  52. @DisplayName("it is no longer empty")
  53. void isNotEmpty() {
  54. assertFalse(stack.isEmpty());
  55. }
  56. @Test
  57. @DisplayName("returns the element when popped and is empty")
  58. void returnElementWhenPopped() {
  59. assertEquals(anElement, stack.pop());
  60. assertTrue(stack.isEmpty());
  61. }
  62. @Test
  63. @DisplayName("returns the element when peeked but remains not empty")
  64. void returnElementWhenPeeked() {
  65. assertEquals(anElement, stack.peek());
  66. assertFalse(stack.isEmpty());
  67. }
  68. }
  69. }
  70. }

6.参数化测试

参数化测试是JUnit5很重要的一个新特性,它使得用不同的参数多次运行测试成为了可能,也为我们的单元测试带来许多便利。

利用@ValueSource等注解,指定入参,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。

@ValueSource: 为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型

@NullSource: 表示为参数化测试提供一个null的入参

@EnumSource: 表示为参数化测试提供一个枚举入参

@CsvFileSource:表示读取指定CSV文件内容作为参数化测试入参

@MethodSource:表示读取指定方法的返回值作为参数化测试入参(注意方法返回需要是一个流)


7.JUnit4 → Junit5

JUnit 5 User Guide

在进行迁移的时候需要注意如下的变化:

  • 注解在 org.junit.jupiter.api 包中,断言在 org.junit.jupiter.api.Assertions 类中,前置条件在 org.junit.jupiter.api.Assumptions 类中。
  • 把@Before 和@After 替换成@BeforeEach 和@AfterEach。
  • 把@BeforeClass 和@AfterClass 替换成@BeforeAll 和@AfterAll。
  • 把@Ignore 替换成@Disabled。
  • 把@Category 替换成@Tag。
  • 把@RunWith、@Rule 和@ClassRule 替换成@ExtendWith。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/712406
推荐阅读
相关标签
  

闽ICP备14008679号