3

I wonder how to configure an extension by a test.

Scenario: The test provides a value that should be used inside the extension.

Current Solution: The value is defined as field inside the test and used by the extension thru scanning all declared fields and pick the correct one (reflection).

Problem: This solution is very indirect. People using this extension must know about extension internals and declare the correct fields (type and value). Errors can lead the developer into the right direction, but its a bit of pain by try/error.

Is there a way to use e.g. annotation with value to configure a junit5 extension?

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
R4FT3R
  • 69
  • 1
  • 8

1 Answers1

3

You may either provide configuration parameters and access them via the ExtensionContext at runtime or since 5.1 there's a programmatic way to register customized extension instances via @RegisterExtension.

Example copied from the JUnit 5 User-Guide:

@RegisterExtension
static WebServerExtension server = WebServerExtension.builder()
    .enableSecurity(false)
    .build();

@Test
void getProductList() {
    WebClient webClient = new WebClient();
    String serverUrl = server.getServerUrl();
    // Use WebClient to connect to web server using serverUrl and verify response
    assertEquals(200, webClient.get(serverUrl + "/products").getResponseStatus());
}
Sormuras
  • 8,491
  • 1
  • 38
  • 64
  • Thanks for your answer. It worth updating to version 5.1 :) I found another [solution](https://github.com/JeffreyFalgout/junit5-extensions/blob/master/extension-testing/src/main/java/name/falgout/jeffrey/testing/junit/testing/ExpectFailureExceptionHandler.java), which reflects a way out of my problem also. – R4FT3R Feb 26 '18 at 15:38
  • 1
    This works for an entire class but what if I want it on a per method basis? – dtc Aug 27 '21 at 21:34