可以通过 @RegisterExtension 在编程方式将 Junit5 扩展添加到 @TestTemplate 测试吗?

huangapple go评论42阅读模式
英文:

Is it possible to add Junit5 extensions programmatically to a @TestTemplate test using @RegisterExtension?

问题

使用 Junit 版本 5.9.2,我正在尝试以编程方式为带有 @TestTemplate 注解的测试类构造函数添加参数解析器扩展,我正在尝试使用 @RegisterExtension 来编程方式添加这些扩展。

示例:

public class MyTestClass {

  @RegisterExtension
  static final TestDependencyResolver resolverExt = new TestDependencyResolver(/*...*/);
  
  private final TestDependency dependency;

  public MyTestClass(TestDependency dependency) {
    this.dependency = dependency;
  }

  @TestTemplate
  @ExtendWith(SomeContextProvider.class)
  void test() {
    //...
  }
}

我已经尝试过:

  1. resolverExt 字段设置为非静态。
  2. @ExtendWith(SomeContextProvider.class) 移到类级别。

以及其他 1 和 2 的可能组合。

在所有情况下,构造函数参数 dependency 都没有被注入,并且 TestDependencyResolver::resolveParameter 也没有被调用,根据我的理解,这意味着对象是在注册 TestDependencyResolver 之前/之外创建的。如果我理解有误,请纠正我。我所尝试的目标是否可行?谢谢。

英文:

Using Junit version 5.9.2 I am trying to programmatically add parameter resolvers extension for a test class constructor with a @TestTemplate annotation.
I am trying to add the extensions programmatically using @RegisterExtension.

Example:

public class MyTestClass {

  @RegisterExtension
  static final TestDependencyResolver resolverExt = new TestDependencyResolver(/*...*/);
  
  private final TestDependency dependency;

  public MyTestClass(TestDependency dependency) {
    this.dependency = dependency;
  }

  @TestTemplate
  @ExtendWith(SomeContextProvider.class)
  void test() {
    //...
  }
}

I have tried:

  1. making resolverExt field non static
  2. Movine @ExtendWith(SomeContextProvider.class) to class level

And other possible combinations of 1 and 2.

In all cases the ctor parameter dependency is not injected and TestDependencyResolver::resolveParameter is not called, which to my understanding means the object was created without/before registering TestDependencyResolver, please correct me if I am wrong.

Is what I am trying to achieve possible? thanks.

答案1

得分: 0

问题原来不是JUnit5,而是我在使用的TestTemplateInvocationContextProvider

我使用了PactVerificationInvocationContextProvider,它似乎有一个bug,在解析构造函数参数时会抛出NullPointerException,如果你想了解更多细节,我已经为此问题提出了一个问题

英文:

Turns out the issue was not Junit5 but TestTemplateInvocationContextProvider I was using.

I used PactVerificationInvocationContextProvider which seems to have a bug and throws NullPointerException when resolving Ctor params, I have opened an issue for it if you want more details.

huangapple
  • 本文由 发表于 2023年2月8日 17:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定