javajunit5allurejunit5-extension-model

How to return value to @Test from junit extension?


I have tests with allure2 @Tmslink("1234") annotaion on each @Test. So, i need to get @TmsLink value and use it in my tests. I've got annotation value in extension, but how can i provide it to test?

public class TmsLink implements BeforeTestExecutionCallback {

    private String tmsLink;

    @Override
    public void beforeTestExecution(ExtensionContext context)  {
        findAnnotation(context.getElement(), TmsLink.class).ifPresent(link -> this.tmsLink = link.value());
    }    
    public String getTmsLink() {
        return tmsLink;
    }
}

@ExtendWith(TmsLink .class)
public abstract class Tests {

}

With Junit4 it's just:

@Rule 
public TmsLink extension = new TmsLink();
extension.getTmsLink();

Solution

  • JUnit Jupiter also supports registering extensions programmatically by annotating fields in test classes with @RegisterExtension:

    class WebServerDemo {
    
        @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());
        }
    
    }
    

    For details please consult the User-Guide at https://junit.org/junit5/docs/current/user-guide/#extensions-registration-programmatic

    Or let your extension also implement ParameterResolver and inject TmsLink as an argument to your test method parameter. Find details and an example linked at https://junit.org/junit5/docs/current/user-guide/#extensions-parameter-resolution