服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - JUnit 5中扩展模型的深入理解

JUnit 5中扩展模型的深入理解

2021-05-28 13:28无明 Java教程

几乎所有的Java 开发人员都会使用JUnit 来做测试,但其实很多自动化测试人员也会使用Junit 。下面这篇文章主要给大家介绍了关于JUnit 5中扩展模型的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

什么是junit5 ?

先看来个公式:

junit 5 = junit platform + junit jupiter + junit vintage

这看上去比junit4 复杂,实际上在导入包时也会复杂一些。

junit platform是在jvm上启动测试框架的基础。

junit jupiter是junit5扩展的新的编程模型和扩展模型,用来编写测试用例。jupiter子项目为在平台上运行jupiter的测试提供了一个testengine (测试引擎)。

junit vintage提供了一个在平台上运行junit 3和junit 4的testengine 。

关键要点

  • junit 5是一个模块化和可扩展的测试框架,支持java 8及更高版本。
  • junit 5由三个部分组成——一个基础平台、一个新的编程和扩展模型jupiter,以及一个名为vintage的向后兼容的测试引擎。
  • junit 5 jupiter的扩展模型可用于向junit中添加自定义功能。
  • 扩展模型api测试生命周期提供了钩子和注入自定义参数的方法(即依赖注入)。

junit是最受欢迎的基于jvm的测试框架,在第5个主要版本中进行了彻底的改造。junit 5提供了丰富的功能——从改进的注解、标签和过滤器到条件执行和对断言消息的惰性求值。这让基于tdd编写单元测试变得轻而易举。新框架还带来了一个强大的扩展模型。扩展开发人员可以使用这个新模型向junit 5中添加自定义功能。本文将指导你完成自定义扩展的设计和实现。这种自定义扩展机制为java程序员提供了一种创建和执行故事和行为(即bdd规范测试)的方法。

我们首先使用junit 5和我们的自定义扩展(称为“storyextension”)来编写一个示例故事和行为(测试方法)。这个示例使用了两个新的自定义注解“@story”和“@scenario”,以及“scene”类,用以支持我们的自定义storyextension:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import org.junit.jupiter.api.extension.extendwith;
 
import ud.junit.bdd.ext.scenario;
import ud.junit.bdd.ext.scene;
import ud.junit.bdd.ext.story;
import ud.junit.bdd.ext.storyextension;
 
@extendwith(storyextension.class)
@story(name=“returns go back to the stockpile”, description=“...“)
public class storefronttest {
 
 @scenario(“refunded items should be returned to the stockpile”)
 public void refundeditemsshouldberestocked(scene scene) {
  scene
   .given(“customer bought a blue sweater”,
      () -> buysweater(scene, “blue”))
 
   .and(“i have three blue sweaters in stock”,
      () -> assertequals(3, sweatercount(scene, “blue”),
        “store should carry 3 blue sweaters”))
 
   .when(“the customer returns the blue sweater for a refund”,
      () -> refund(scene, 1, “blue”))
 
   .then(“i should have four blue sweaters in stock”,
      () -> assertequals(4, sweatercount(scene, “blue”),
        “store should carry 4 blue sweaters”))
   .run();
 }
}

从代码片段中我们可以看到,jupiter的扩展模型非常强大。我们还可以看到,我们的自定义扩展及其相应的注解为测试用例编写者提供了简单而干净的方法来编写bdd规范。

作为额外的奖励,当使用我们的自定义扩展程序执行测试时,会生成如下所示的文本报告:

story: returns go back to the stockpile
 
as a store owner, in order to keep track of stock, i want to add items back to stock when they're returned.
 
scenario: refunded items should be returned to stock
   given that a customer previously bought a blue sweater from me
     and i have three blue sweaters in stock
    when the customer returns the blue sweater for a refund
    then i should have four blue sweaters in stock

这些报告可以作为应用程序功能集的文档。

自定义扩展storyextension能够借助以下核心概念来支持和执行故事和行为:

  • 用于装饰测试类和测试方法的注解
  • junit 5 jupiter的生命周期回调
  • 动态参数解析

注解

示例中的“@extendwith”注解是由jupiter提供的标记接口。这是在测试类或方法上注册自定义扩展的方法,目的是让jupiter测试引擎调用给定类或方法的自定义扩展。或者,测试用例编写者可以通过编程的方式注册自定义扩展,或者通过服务加载器机制进行自动注册。

我们的自定义扩展需要一种识别故事的方法。为此,我们定义了一个名为“story”的自定义注解类,如下所示:

?
1
2
3
4
import org.junit.platform.commons.annotation.testable;
 
@testable
public @interface story {...}

测试用例编写者应该使用这个自定义注解将测试类标记为故事。请注意,这个注解本身使用了junit 5内置的“@testable”注解。这个注解为ide和其他工具提供了一种识别可测试的类和方法的方式——也就是说,带有这个注解的类或方法可以通过junit 5 jupiter测试引擎来执行。

我们的自定义扩展还需要一种方法来识别故事中的行为或场景。为此,我们定义一个名为“scenario”的自定义注解类,看起来像这样:

?
1
2
3
4
import org.junit.jupiter.api.test;
 
@test
public @interface scenario {...}

测试用例编写者应使用这个自定义注解将测试方法标记为场景。这个注解本身使用了junit 5 jupiter的内置“@test”注解。当ide和测试引擎扫描给定的一组测试类并在公共实例方法上找到@scenario注解时,就会将这些方法标记为可执行的测试方法。

请注意,与junit 4的@test注解不同,jupiter的@test注解不支持可选的“预期”异常和“超时”参数。jupiter的@test注解是从头开始设计的,并考虑到了可扩展性。

生命周期

junit 5 jupiter提供了扩展回调,可用于访问测试生命周期事件。扩展模型提供了几个接口,用于在测试执行生命周期的各个时间点对测试进行扩展:

JUnit 5中扩展模型的深入理解

扩展开发者可以自由地实现所有或部分生命周期接口。

“beforeallcallback”接口提供了一种方法用于初始化扩展并在调用junit测试容器中的测试用例之前添加自定义逻辑。我们的storyextension类将实现这个接口,以确保给定的测试类使用了“@story”注解。

?
1
2
3
4
5
6
7
8
9
10
11
12
import org.junit.jupiter.api.extension.beforeallcallback;
 
public class storyextension implements beforeallcallback {
 @override
 public void beforeall(extensioncontext context) throws exception {
 
  if (!annotationsupport
    .isannotated(context.getrequiredtestclass(), story.class)) {
   throw new exception(“use @story annotation...“);
  }
 }
}

jupiter引擎将提供一个用于运行扩展的执行上下文。我们使用这个上下文来确定正在执行的测试类是否使用了“@story”注解。我们使用junit平台提供的annotationsupport辅助类来检查是否存在这个注解。

回想一下,我们的自定义扩展在执行测试后会生成bdd报告。这些报告的某些部分是从“@store”注解的元素中提取的。我们使用beforeall回调来保存这些字符串。稍后,在执行生命周期结束时,再基于这些字符串生成报告。我们使用了一个简单的pojo。我们将这个类命名为“storyde​​tails”。以下代码片段演示了创建这个类实例的过程,并将注解元素保存到实例中:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class storyextension implements beforeallcallback {
 @override
 public void beforeall(extensioncontext context) throws exception {
 
  class<?> clazz = context.getrequiredtestclass();
  story story = clazz.getannotation(story.class);
 
  storydetails storydetails = new storydetails()
    .setname(story.name())
    .setdescription(story.description())
    .setclassname(clazz.getname());
 
  context.getstore(namespace).put(clazz.getname(), storydetails);
 }
}

我们需要解释一下方法的最后一个语句。我们实际上是从执行上下文中获取一个带有名字的存储,并将新创建的“storyde​​tails”实例保存到这个存储中。

自定义扩展可以使用存储来保存和获取任意数据——基本上就是一个存在于内存中的map。为了避免多个扩展之间出现意外的key冲突,junit引入了命名空间的概念。命名空间是一种对不同扩展保存的数据进行隔离的方法。用于隔离扩展数据的一种常用方法是使用自定义扩展类名:

?
1
2
private static final namespace namespace = namespace
   .create(storyextension.class);

我们的扩展需要用到的另一个自定义注解是“@scenario”注解。这个注解用于将测试方法标记为故事中的场景或行为。我们的扩展将解析这些场景,以便将它们作为junit测试用例来执行并生成报告。回想一下我们之前看到的生命周期图中的“beforeeachcallback”接口,在调用每个测试方法之前,我们将使用回调来添加附加逻辑:

?
1
2
3
4
5
6
7
8
9
10
11
import org.junit.jupiter.api.extension.beforeeachcallback;
 
public class storyextension implements beforeeachcallback {
 @override
 public void beforeeach(extensioncontext context) throws exception {
  if (!annotationsupport.
   isannotated(context.getrequiredtestmethod(), scenario.class)) {
    throw new exception(“use @scenario annotation...“);
  }
 }
}

如前所述,jupiter引擎将提供一个用于运行扩展的执行上下文。我们使用上下文来确定正在执行的测试方法是否使用了“@scenario”注解。

回到本文的开头,我们提供了一个故事的示例代码,我们的自定义扩展负责将“scene”类的实例注入到每个测试方法中。scene类让测试用例编写者能够使用“given”、“then”和“when”等步骤来定义场景(行为)。scene类是我们自定义扩展的中心单元,它包含了特定于测试方法的状态信息。状态信息可以在场景的各个步骤之间传递。我们使用“beforeeachcallback”接口在调用测试方法之前准备一个scene实例:如前所述,jupiter引擎将提供一个用于运行扩展执行上下文。我们使用上下文来确定正在执行的测试方法是否使用了“@scenario”注解。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class storyextension implements beforeeachcallback {
 @override
 public void beforeeach(extensioncontext context) throws exception {
  scene scene = new scene()
    .setdescription(getvalue(context, scenario.class));
 
  class<?> clazz = context.getrequiredtestclass();
 
  storydetails details = context.getstore(namespace)
    .get(clazz.getname(), storydetails.class);
 
  details.put(scene.getmethodname(), scene);
 }
}

上面的代码与我们在“beforeallcallback”接口方法中所做的非常相似。

动态参数解析

现在我们还缺少一个东西,即如何将场景实例注入到测试方法中。jupiter的扩展模型为我们提供了一个“parameterresolver”接口。这个接口为测试引擎提供了一种方法,用于识别希望在测试执行期间动态注入参数的扩展。我们需要实现这个接口的两个方法,以便注入我们的场景实例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.junit.jupiter.api.extension.parameterresolver;
 
public class storyextension implements parameterresolver {
 @override
 public boolean supportsparameter(parametercontext parametercontext,
          extensioncontext extensioncontext) {
  parameter parameter = parametercontext.getparameter();
 
  return scene.class.equals(parameter.gettype());
 }
 
 @override
 public object resolveparameter(parametercontext parametercontext,
         extensioncontext extensioncontext) {
  class<?> clazz = extensioncontext.getrequiredtestclass();
 
  storydetails details = extensioncontext.getstore(namespace)
    .get(clazz.getname(), storydetails.class);
 
  return details.get(extensioncontext
       .getrequiredtestmethod().getname());
 }
}

上面的第一个方法告诉jupiter我们的自定义扩展是否可以注入测试方法所需的参数。

在第二个方法“resolveparameter()”中,我们从执行上下文的存储中获取storyde​​tails实例,然后从storydetails实例中获取先前为给定测试方法创建的场景实例,并将其传给测试引擎。测试引擎将这个场景实例注入到测试方法中并执行测试。请注意,仅当“supportsparameter()”方法返回true值时才会调用“resolveparameter()”方法。

最后,为了在执行完所有故事和场景后生成报告,自定义扩展实现了“afterallcallback”接口:

?
1
2
3
4
5
6
7
8
9
import org.junit.jupiter.api.extension.afterallcallback;
 
public class storyextension implements afterallcallback {
 @override
 public void afterall(extensioncontext context) throws exception {
 
  new storywriter(getstorydetails(context)).write();
 }
}

“storywriter”是一个自定义类,可生成报告并将其保存到json或文本文件中。

现在,让我们看看如何使用这个自定义扩展来编写bdd风格的测试用例。gradle 4.6及更高版本支持使用junit 5运行单元测试。你可以使用build.gradle文件来配置junit 5。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
dependencies {
 testcompile group: “ud.junit.bdd”, name: “bdd-junit”,
    version: “0.0.1-snapshot”
 
 testcompile group: “org.junit.jupiter”, name: “junit-jupiter-api”,
    version: “5.2.0"
 testruntime group: “org.junit.jupiter”, name: “junit-jupiter-engine”,
    version: “5.2.0
}
 
test {
 usejunitplatform()
}

如你所见,我们通过“usejunitplatform()”方法要求gradle使用junit 5。然后我们就可以使用storyextension类来编写测试用例。这是本文开头给出的示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import org.junit.jupiter.api.extension.extendwith;
 
import ud.junit.bdd.ext.scenario;
import ud.junit.bdd.ext.story;
import ud.junit.bdd.ext.storyextension;
 
@extendwith(storyextension.class)
@story(name=“returns go back to the stockpile”, description=“...“)
public class storefronttest {
 
 @scenario(“refunded items should be returned to the stockpile”)
 public void refundeditemsshouldberestocked(scene scene) {
  scene
   .given(“customer bought a blue sweater”,
      () -> buysweater(scene, “blue”))
 
   .and(“i have three blue sweaters in stock”,
      () -> assertequals(3, sweatercount(scene, “blue”),
        “store should carry 3 blue sweaters”))
 
   .when(“the customer returns the blue sweater for a refund”,
      () -> refund(scene, 1, “blue”))
 
   .then(“i should have four blue sweaters in stock”,
      () -> assertequals(4, sweatercount(scene, “blue”),
        “store should carry 4 blue sweaters”))
   .run();
 }
}

我们可以通过“gradle testclasses”来运行测试,或者使用其他支持junit 5的ide。除了常规的测试报告外,自定义扩展还为所有测试类生成bdd文档。

结论

我们描述了junit 5扩展模型以及如何利用它来创建自定义扩展。我们设计并实现了一个自定义扩展,测试用例编写者可以使用它来创建和执行故事。读者可以从github上获取代码,并研究如何使用jupiter扩展模型及其api来实现自定义扩展。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.infoq.com/cn/articles/deep-dive-junit5-extensions

延伸 · 阅读

精彩推荐