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

本文详细介绍了JUnit5中的条件注解,如自定义条件EnabledIf和DisabledIf,以及内置的针对操作系统、JRE版本和系统属性的条件。此外,还涵盖嵌套测试和重复测试功能,展示了如何利用这些特性提高测试灵活性。
摘要由CSDN通过智能技术生成

条件测试

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. }

  11. 现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。

  12. 如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受

  13. 可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛

  14. 分享他们的经验,还会分享很多直播讲座和技术沙龙

  15. 可以免费学习!划重点!开源的!!!

  16. qq群号:680748947

嵌套测试

嵌套测试可以帮助我们对测试结构进行分层。借助于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还支持另一个重要且常见的测试:参数化测试。

 

总结:

感谢每一个认真阅读我文章的人!!!

作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

软件测试面试文档

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

 

          视频文档获取方式:
这份文档和视频资料,对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!以上均可以分享,点下方小卡片即可自行领取。

  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值