Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit 5, pass information from test class to extension

I am trying to write an extension for Junit5 similar to what I had for Junit4 but I am failing to grasp how to do that in the new (stateless) extension system.

The idea in the previous version was that user could pass information into extension class and hence change the way it behaved. Here is a pseudo snippet showing approximately what is used to do:

public void MyTest {

  // here I can define different behaviour for my extension
  @Rule MyCustomRule rule = MyCustomRule.of(Foo.class).withPackage(Bar.class.getPackage).alsoUse(Cookies.class);

  @Test
  public void someTest() {
    // some test code already affected by the @Rule
    // plus, user has access to that class and can use it, say, retrieve additional information
    rule.grabInfoAboutStuff();
  }
}

Now, I know how to operate JUnit 5 extension, what lifecycles to use etc. But I don't know how to give the test-writer the power to modify my extension's behaviour with JUnit5. Any pointers appreciated.

like image 998
Siliarus Avatar asked Oct 21 '25 12:10

Siliarus


2 Answers

As of JUnit Jupiter 5.0.1, it is unfortunately not possible to pass parameters to an Extension programmatically like you could for rules in JUnit 4.

However, I am working on adding such support in JUnit Jupiter 5.1. You can follow the following issue if you like: https://github.com/junit-team/junit5/issues/497

In the interim, the only way to pass information to an extension is for the extension to support custom annotations and extract the user-supplied information from there. For example, I allow users to provide a custom SpEL expression in the @EnabledIf annotation in the Spring Framework, and my ExecutionCondition extension pulls the expression from the annotation using reflection.

like image 74
Sam Brannen Avatar answered Oct 23 '25 01:10

Sam Brannen


followup on the (accepted) answer from Sam as in the meantime the referred bug has been implemented with junit 5.1

  • use @RegisterExtension
  • see https://junit.org/junit5/docs/current/user-guide/#extensions-registration-programmatic
like image 28
elonderin Avatar answered Oct 23 '25 01:10

elonderin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!