写点什么

Junit5 架构、新特性及基本使用(常用注解与套件执行)

  • 2022 年 9 月 30 日
    北京
  • 本文字数:1144 字

    阅读完需:约 4 分钟

什么是 Junit5,在 Junit5 的官方介绍文档中这写到:Junit5 由 JUnit Platform + JUnit Jupiter + JUnit Vintage3 部分构成,借用 IBM Developer 的一张图来说明 JUnit 5 的架构:JUnit Platform:JUnit Jupiter:JUnit Vintage:

  • 嵌套单元测试

  • Lambda 支持

  • 参数化测试

  • 重复测试

  • 动态测试


    JUnit 4 与 JUnit 5 中的注解比较



  • 1)创建 maven 工程 XUnit,pom.xml 中添加 Junit5 的依赖。

  • 2)其余的 XUnit 框架通用的设计运行规则可参考:《如何利用 xUnit 框架对测试用例进行维护》。

  • 3)添加用例 @Test,再在用例执行前后添加 @BeforeEach、@AfterEach:

  • 运行结果:

  • 4)在测试类执行前后添加 @BeforeAll 和 @AfterAll:

  • 测试结果:

  • 5)在测试用例 test1 上加入注解 @Disabled,使 test1 失效。

  • 测试结果:

  • 从测试结果中我们可以看到 test1 用例被 ignore,没有被执行。

  • 6)分别将 test1 和 test2 用 @DisplayName 加上用例展示名称。

  • 测试结果:

  • 7)对测试用例 2 加上注解 @RepeatedTest,使其额外重复执行 3 次:

  • 测试结果:

  • 从测试结果中我们可以看到测试用例 2 被额外重复执行了 3 次

  • 8)对于 @Nested 嵌套执行举例如下:

  • 测试结果:

  • 由测试结果可以看出,@Nested 的执行顺序为先执行 @Nested 嵌套外层的用例,再以倒叙形式执行 @Nested 用例,然后再执行第二层嵌套的用例:外层->倒叙嵌套->第二层嵌套。

@RunWith 是从 Junit4 迁移过来的,@RunWith 连同它的参数 JUnitPlatform.class(一个基于 JUnit 4 且理解 JUnit Platform 的 Runner)让您可以在 Eclipse 内运行 JUnit Jupiter 单元测试。Eclipse 尚未原生支持 JUnit 5。未来,Eclipse 将提供原生的 JUnit 5 支持,那时我们不再需要此注解;Junit5 官方给出了替代它的注解:

  • 有两个包 testcasedemo, junit5demo,利用 @RunWith+@SelectPackages 将包中测试类依次运行。

  • 套件类:

  • 测试结果:

  • @RunWith+@SelectPackages+@IncludePackages 配合使用过滤出需要执行的测试包 testcasedemo.demo2。

  • 套件类:

  • 测试结果:

  • @RunWith+@SelectPackages+@ExcludePackages 配合使用过滤出不需要执行的测试包 testcasedemo.demo2。

  • 套件类:

  • 测试结果:

  • 将 junit5demo 包下的 TestJunit5demo 和 testcasedemo.demo2 所有测试类过滤出来并执行。

  • 套件类:

  • 测试结果:

  • 在 testcasedemo.demo2.TestDemo2 的方法 testDemo2 上加上注解 @Tag:

  • 过滤并执行方法 testDemo2:

  • 套件类:

  • 测试结果:

  • Junit5 官网:

  • JUnit 5 User Guide

  • IBM Developer:

  • https://www.ibm.com/developerworks/cn/java/j-introducing-junit5-part1-jupiter-api/index.html

  • https://www.ibm.com/developerworks/cn/java/j-junit5/index.html

Junit5 在特性上已经超越 TestNG 了,会成为未来 Java 届的首选测试框架。

更多学习资料戳下方!!!

https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=infoQ&timestamp=1662366626&author=xueqi

用户头像

社区:ceshiren.com 2022.08.29 加入

微信公众号:霍格沃兹测试开发 提供性能测试、自动化测试、测试开发等资料、实事更新一线互联网大厂测试岗位内推需求,共享测试行业动态及资讯,更可零距离接触众多业内大佬

评论

发布
暂无评论
Junit5 架构、新特性及基本使用(常用注解与套件执行)_测试_测吧(北京)科技有限公司_InfoQ写作社区