• JUnit5的条件测试、嵌套测试、重复测试


    条件测试

    JUnit5支持条件注解,根据布尔值判断是否执行测试。

    自定义条件

    @EnabledIf@DisabledIf注解用来设置自定义条件,示例:

    1. @Test
    2. @EnabledIf("customCondition")
    3. void enabled() {
    4. // ...
    5. }
    6. @Test
    7. @DisabledIf("customCondition")
    8. void disabled() {
    9. // ...
    10. }
    11. boolean customCondition() {
    12. return true;
    13. }

    其中customCondition()方法用来返回布尔值,它可以接受一个ExtensionContext类型的参数。如果定义在测试类外部,那么需要是static方法。

    内置条件

    JUnit5的org.junit.jupiter.api.condition包中内置了一些条件注解。

    操作系统条件

    @EnabledOnOsDisabledOnOs,示例:

    1. @Test
    2. @EnabledOnOs(MAC)
    3. void onlyOnMacOs() {
    4. // ...
    5. }
    6. @TestOnMac
    7. void testOnMac() {
    8. // ...
    9. }
    10. @Test
    11. @EnabledOnOs({ LINUX, MAC })
    12. void onLinuxOrMac() {
    13. // ...
    14. }
    15. @Test
    16. @DisabledOnOs(WINDOWS)
    17. void notOnWindows() {
    18. // ...
    19. }
    20. @Target(ElementType.METHOD)
    21. @Retention(RetentionPolicy.RUNTIME)
    22. @Test
    23. @EnabledOnOs(MAC)
    24. @interface TestOnMac {
    25. }

    JRE条件

    @EnabledOnJre@DisabledOnJre用于指定版本,@EnabledForJreRange@DisabledForJreRange用于指定版本范围,示例:

    1. @Test
    2. @EnabledOnJre(JAVA_8)
    3. void onlyOnJava8() {
    4. // ...
    5. }
    6. @Test
    7. @EnabledOnJre({ JAVA_9, JAVA_10 })
    8. void onJava9Or10() {
    9. // ...
    10. }
    11. @Test
    12. @EnabledForJreRange(min = JAVA_9, max = JAVA_11)
    13. void fromJava9to11() {
    14. // ...
    15. }
    16. @Test
    17. @EnabledForJreRange(min = JAVA_9)
    18. void fromJava9toCurrentJavaFeatureNumber() {
    19. // ...
    20. }
    21. @Test
    22. @EnabledForJreRange(max = JAVA_11)
    23. void fromJava8To11() {
    24. // ...
    25. }
    26. @Test
    27. @DisabledOnJre(JAVA_9)
    28. void notOnJava9() {
    29. // ...
    30. }
    31. @Test
    32. @DisabledForJreRange(min = JAVA_9, max = JAVA_11)
    33. void notFromJava9to11() {
    34. // ...
    35. }
    36. @Test
    37. @DisabledForJreRange(min = JAVA_9)
    38. void notFromJava9toCurrentJavaFeatureNumber() {
    39. // ...
    40. }
    41. @Test
    42. @DisabledForJreRange(max = JAVA_11)
    43. void notFromJava8to11() {
    44. // ...
    45. }

    JVM系统属性条件

    @EnabledIfSystemProperty@DisabledIfSystemProperty,示例:

    1. @Test
    2. @EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*")
    3. void onlyOn64BitArchitectures() {
    4. // ...
    5. }
    6. @Test
    7. @DisabledIfSystemProperty(named = "ci-server", matches = "true")
    8. void notOnCiServer() {
    9. // ...
    10. }

    环境变量条件

    @EnabledIfEnvironmentVariable@DisabledIfEnvironmentVariable,示例:

    1. @Test
    2. @EnabledIfEnvironmentVariable(named = "ENV", matches = "staging-server")
    3. void onlyOnStagingServer() {
    4. // ...
    5. }
    6. @Test
    7. @DisabledIfEnvironmentVariable(named = "ENV", matches = ".*development.*")
    8. void notOnDeveloperWorkstation() {
    9. // ...
    10. }
    1. 现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
    2. 如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
    3. 可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
    4. 分享他们的经验,还会分享很多直播讲座和技术沙龙
    5. 可以免费学习!划重点!开源的!!!
    6. qq群号:110685036

    嵌套测试

    嵌套测试可以帮助我们对测试结构进行分层。借助于Java嵌套类的语法,JUnit5可以通过@Nested注解,实现嵌套测试,示例:

    1. import static org.junit.jupiter.api.Assertions.assertEquals;
    2. import static org.junit.jupiter.api.Assertions.assertFalse;
    3. import static org.junit.jupiter.api.Assertions.assertThrows;
    4. import static org.junit.jupiter.api.Assertions.assertTrue;
    5. import java.util.EmptyStackException;
    6. import java.util.Stack;
    7. import org.junit.jupiter.api.BeforeEach;
    8. import org.junit.jupiter.api.DisplayName;
    9. import org.junit.jupiter.api.Nested;
    10. import org.junit.jupiter.api.Test;
    11. @DisplayName("A stack")
    12. class TestingAStackDemo {
    13. Stack<Object> stack;
    14. @Test
    15. @DisplayName("is instantiated with new Stack()")
    16. void isInstantiatedWithNew() {
    17. new Stack<>();
    18. }
    19. @Nested
    20. @DisplayName("when new")
    21. class WhenNew {
    22. @BeforeEach
    23. void createNewStack() {
    24. stack = new Stack<>();
    25. }
    26. @Test
    27. @DisplayName("is empty")
    28. void isEmpty() {
    29. assertTrue(stack.isEmpty());
    30. }
    31. @Test
    32. @DisplayName("throws EmptyStackException when popped")
    33. void throwsExceptionWhenPopped() {
    34. assertThrows(EmptyStackException.class, stack::pop);
    35. }
    36. @Test
    37. @DisplayName("throws EmptyStackException when peeked")
    38. void throwsExceptionWhenPeeked() {
    39. assertThrows(EmptyStackException.class, stack::peek);
    40. }
    41. @Nested
    42. @DisplayName("after pushing an element")
    43. class AfterPushing {
    44. String anElement = "an element";
    45. @BeforeEach
    46. void pushAnElement() {
    47. stack.push(anElement);
    48. }
    49. @Test
    50. @DisplayName("it is no longer empty")
    51. void isNotEmpty() {
    52. assertFalse(stack.isEmpty());
    53. }
    54. @Test
    55. @DisplayName("returns the element when popped and is empty")
    56. void returnElementWhenPopped() {
    57. assertEquals(anElement, stack.pop());
    58. assertTrue(stack.isEmpty());
    59. }
    60. @Test
    61. @DisplayName("returns the element when peeked but remains not empty")
    62. void returnElementWhenPeeked() {
    63. assertEquals(anElement, stack.peek());
    64. assertFalse(stack.isEmpty());
    65. }
    66. }
    67. }
    68. }

    外部测试类通过@BeforeEach向内部测试类传递变量。

    执行后结果:

    writing tests nested test ide

    重复测试

    @RepeatedTest注解能控制测试方法的重复执行次数,示例:

    1. import static org.junit.jupiter.api.Assertions.assertEquals;
    2. import java.util.logging.Logger;
    3. import org.junit.jupiter.api.BeforeEach;
    4. import org.junit.jupiter.api.DisplayName;
    5. import org.junit.jupiter.api.RepeatedTest;
    6. import org.junit.jupiter.api.RepetitionInfo;
    7. import org.junit.jupiter.api.TestInfo;
    8. class RepeatedTestsDemo {
    9. private Logger logger = // ...
    10. @BeforeEach
    11. void beforeEach(TestInfo testInfo, RepetitionInfo repetitionInfo) {
    12. int currentRepetition = repetitionInfo.getCurrentRepetition();
    13. int totalRepetitions = repetitionInfo.getTotalRepetitions();
    14. String methodName = testInfo.getTestMethod().get().getName();
    15. logger.info(String.format("About to execute repetition %d of %d for %s", //
    16. currentRepetition, totalRepetitions, methodName));
    17. }
    18. @RepeatedTest(10)
    19. void repeatedTest() {
    20. // ...
    21. }
    22. @RepeatedTest(5)
    23. void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
    24. assertEquals(5, repetitionInfo.getTotalRepetitions());
    25. }
    26. @RepeatedTest(value = 1, name = "{displayName} {currentRepetition}/{totalRepetitions}")
    27. @DisplayName("Repeat!")
    28. void customDisplayName(TestInfo testInfo) {
    29. assertEquals("Repeat! 1/1", testInfo.getDisplayName());
    30. }
    31. @RepeatedTest(value = 1, name = RepeatedTest.LONG_DISPLAY_NAME)
    32. @DisplayName("Details...")
    33. void customDisplayNameWithLongPattern(TestInfo testInfo) {
    34. assertEquals("Details... :: repetition 1 of 1", testInfo.getDisplayName());
    35. }
    36. @RepeatedTest(value = 5, name = "Wiederholung {currentRepetition} von {totalRepetitions}")
    37. void repeatedTestInGerman() {
    38. // ...
    39. }
    40. }

    其中name可以用来自定义重复测试的显示名字,{currentRepetition}{totalRepetitions}是当前次数和总共次数的变量。

    执行结果:

    1. ├─ RepeatedTestsDemo ✔
    2. │ ├─ repeatedTest() ✔
    3. │ │ ├─ repetition 1 of 10
    4. │ │ ├─ repetition 2 of 10
    5. │ │ ├─ repetition 3 of 10
    6. │ │ ├─ repetition 4 of 10
    7. │ │ ├─ repetition 5 of 10
    8. │ │ ├─ repetition 6 of 10
    9. │ │ ├─ repetition 7 of 10
    10. │ │ ├─ repetition 8 of 10
    11. │ │ ├─ repetition 9 of 10
    12. │ │ └─ repetition 10 of 10
    13. │ ├─ repeatedTestWithRepetitionInfo(RepetitionInfo) ✔
    14. │ │ ├─ repetition 1 of 5
    15. │ │ ├─ repetition 2 of 5
    16. │ │ ├─ repetition 3 of 5
    17. │ │ ├─ repetition 4 of 5
    18. │ │ └─ repetition 5 of 5
    19. │ ├─ Repeat! ✔
    20. │ │ └─ Repeat! 1/1
    21. │ ├─ Details... ✔
    22. │ │ └─ Details... :: repetition 1 of 1
    23. │ └─ repeatedTestInGerman() ✔
    24. │ ├─ Wiederholung 1 von 5
    25. │ ├─ Wiederholung 2 von 5
    26. │ ├─ Wiederholung 3 von 5
    27. │ ├─ Wiederholung 4 von 5
    28. │ └─ Wiederholung 5 von 5

    小结

    本文分别对JUnit5的条件测试、嵌套测试、重复测试进行了介绍,它们可以使得测试更加灵活和富有层次。除了这些,JUnit5还支持另一个重要且常见的测试:参数化测试。

    最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走!

    软件测试面试文档

    我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
     

    在这里插入图片描述

  • 相关阅读:
    企业内部通讯,WorkPlus助您打造高效沟通平台
    【老生谈算法】matlab实现LSB算法水印算法源码——LSB算法
    MATLAB循环结构
    Python 复利计算器
    Golang slice 通过growslice调用nextslicecap计算扩容
    Spring Cloud微服务治理框架深度解析
    【前端甜点】某视频网站的m4s视频/音频下载方案(20240420)
    网络协议
    线程池的实现
    flask bootstrap页面json格式化
  • 原文地址:https://blog.csdn.net/IT_LanTian/article/details/134021225