kwakeroni
kwakeroni

Reputation: 81

How to inject parameters into JUnit 5 extensions

Is it possible to inject (or otherwise obtain) parameters provided by a ParameterResolver into an extension ?

The following example uses Spring and RestAssured, but I'm looking for a more general solution:

In the test class I can do the following:

@BeforeEach
void setUpRestAssured(@LocalServerPort int port) {
    RestAssured.port = port;
}

If I wanted to put this into an extension, I would implement the BeforeEachCallback:

public class RestAssuredExtension implements BeforeEachCallback {
    @Override
    public void beforeEach(ExtensionContext context) throws Exception {
        int port = ???
    }
}

I'm aware I could create a field with the @LocalServerPort annotation and fetch it using AnnotationSupport, but that only works because the Spring extension injects it. I'm looking for a more general approach that would work with other extensions using parameter resolvers.

Upvotes: 4

Views: 1300

Answers (1)

johanneslink
johanneslink

Reputation: 5351

Having gone through the current implementation of lifecycle methods and extensions I don't see a generic way to solve that problem. What Jupiter's extension mechanism would need is a way to access other extensions - or at least registered parameter resolvers. You may want to create an issue at https://github.com/junit-team/junit5 and request that feature.

Upvotes: 0

Related Questions