JUnit5常用注解

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

  • @Test :表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
  • @ParameterizedTest :表示方法是参数化测试,
  • @RepeatedTest :表示方法可重复执行,需要传参数为重复几次,
  • @DisplayName :为测试类或者测试方法设置展示名称
  • @BeforeEach :表示在每个单元测试之前执行
  • @AfterEach :表示在每个单元测试之后执行
  • @BeforeAll :表示在所有单元测试之前执行,该方法必须是静态的。
  • @AfterAll :表示在所有单元测试之后执行,该方法必须是静态的。
  • @Tag :表示单元测试类别,类似于JUnit4中的@Categories
  • @Disabled :表示测试类或测试方法不执行,类似于JUnit4中的@Ignore,此注解对@BeforeEach,@BeforeAll,@AfterEach和@AfterAll没有用,就算加上,方法也会执行。
  • @Timeout :表示测试方法运行如果超过了指定时间将会返回错误
  • @ExtendWith :为测试类或测试方法提供扩展类引用 ```java package com.rit.demo.test;

import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;

import com.rit.demo.pojo.User; import com.rit.demo.service.UserService;

@SpringBootTest public class Tests {

  1. @Autowired
  2. private UserService us;
  3. @Test
  4. @DisplayName("第一次測試")
  5. public void firstTest() {
  6. System.out.println("hello word");
  7. }
  8. @Disabled
  9. @Test
  10. public void T() {
  11. System.out.println("userService=========="+us);
  12. User user=us.queryById(1);
  13. System.out.println(user.getName());
  14. }
  15. @BeforeEach
  16. @DisplayName("每個測試單元之前執行")
  17. public void beforeTest() {
  18. System.out.println("每個測試單元之前執行");
  19. }
  20. @BeforeAll
  21. @DisplayName("每個測試單元之前執行")
  22. public static void beforeAllTest() {
  23. System.out.println("所有測試單元之前執行");
  24. }
  25. @AfterEach
  26. @DisplayName("每個測試單元之后執行")
  27. public void afterTest() {
  28. System.out.println("每個測試單元之后執行");
  29. }
  30. @AfterAll
  31. @DisplayName("所有測試單元之后執行")
  32. @Disabled
  33. public static void afterAllTest() {
  34. System.out.println("所有測試單元之后執行");
  35. }
  36. @Disabled
  37. @DisplayName("此方法不執行")
  38. public void disTest() {
  39. System.out.println("此方法不執行");
  40. }
  41. /**
  42. * @RepeatedTest(5) 裡面參數傳重複次數
  43. * @Title: reTest
  44. * @author Emily1_Zhang
  45. */
  46. @RepeatedTest(5)
  47. @DisplayName("此方法可重複執行")
  48. public void reTest() {
  49. System.out.println("此方法可重複執行");
  50. }

} ```