JUnit 5中的@RuleChain等效于什么?

时间:2018-10-04 12:40:26

标签: java junit junit5 junit5-extension-model

  • 我有2条“班级”规则:MyRule1MyRule2
  • MyRule2取决于MyRule1
  • MyRule1“之前”方法应在MyRule2“之前”方法之前运行。

在JUnit 4中,可以通过RuleChain通过这种方式实现:

static MyRule1 myRule1 = new MyRule1();
static MyRule2 myRule2 = new MyRule2(myRule1);

@Rule
TestRule ruleChain = RuleChain.outerRule(myRule1)
        .around(myRule2);

在JUnit 5中,我必须以这种方式实现它:

static MyRule1 myRule1 = new MyRule1();

@RegisterExtension
static MyRule2 myRule2 = new MyRule2(myRule1);

带有MyRule2

class MyRule2 implements BeforeAllCallback {

    private final MyRule1 myRule1;

    public MyRule2(MyRule1 myRule1) {
        this.myRule1 = myRule1;
    }

    @Override
    public void beforeAll(ExtensionContext extensionContext) {
        this.myRule1.beforeAll();

        X x = this.myRule1.getX();
        // do Rule 2 stuff with x
    }
}

关于结果,它等同于JUnit 4实现。

但是我必须在beforeAll()中显式并手动调用MyRule1的{​​{1}}回调。

我希望MyRule2MyRule2的执行不承担任何责任。

我经历了Extension Model documentation of JUnit 5 但在依赖于其他扩展名的扩展名上未找到任何内容。

2 个答案:

答案 0 :(得分:2)

引用Jupiter's documentation

  

通过@ExtendWith以声明方式注册的扩展名将按照在源代码中声明的顺序执行。

因此,在您的情况下,应按以下顺序声明它们:

@ExtendsWith({Rule1.class, Rule2.class})
public class MyTest {

答案 1 :(得分:1)

对于通过using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.Core.WebApi; using Microsoft.VisualStudio.Services.Client; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; using System; namespace TfsRestAPIs { public class RestAPI { public static void UpdateRetainedByRelaseToFalse() { Uri tfsURI = new Uri("http://TFS2017:8080/tfs/YourProjectCollection"); VssCredentials creds = new VssClientCredentials(); creds.Storage = new VssClientCredentialStorage(); VssConnection connection = new VssConnection(tfsURI, creds); var projectClient = connection.GetClient<ProjectHttpClient>(); var projects = projectClient.GetProjects().Result; var buildClient = connection.GetClient<BuildHttpClient>(); foreach (var project in projects) { Log(project.Name); if (project.Name == "YourProjectName") { var builds = buildClient.GetBuildsAsync(project.Id).Result; foreach (Build build in builds) { if (build.BuildNumber.StartsWith("YourSearchCondition")) try { if (build.RetainedByRelease.Value) { Log(build.BuildNumber + "'s RetainedByRelease=true"); build.RetainedByRelease = false; var res = buildClient.UpdateBuildAsync(build, build.Id).Result; Log(" --> RetainedByRelease is set to " + res.RetainedByRelease.Value); } } catch (Exception e) { Log(build.BuildNumber + ":" + e.Message); } } } } } private static void Log(string msg) { Console.WriteLine(msg); } } } 注册的扩展,(从JUnit Jupiter 5.3.1开始)目前没有类似于JUnit 4的@RegisterExtension的内置支持。

但是,this issue链接到自定义解决方案,并且还建议支持RuleChain,以控制扩展的执行顺序。