Search code examples
junitjunit5

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


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.


Solution

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