Junit5: Provide ExtensionContext as a default ParameterResolver

Created on 20 Feb 2020  路  2Comments  路  Source: junit-team/junit5

Is it possible to have ExtensionContext as part of a default ParameterResolver which could be used in BeforeAll, BeforeEach, AfterEach, AfterAll methods

I know that we can implement Extension classes for beforeEachCallback and similar methods, however in cases where each test class need small or very specific before and after methods or want to use class elements for their implementation, it doesn't make sense to have classes for the same

Be Aware of another request
https://github.com/junit-team/junit5/issues/2191

Deliverables

  • [ ] ... Be able to resolve ExtensionContext as a default ParameterResolver for Before and After Methods
Jupiter invalid extensions

Most helpful comment

Personally, I don't think JUnit Jupiter should supply the ExtensionContext to user-defined lifecycle callback methods, since they are by definition not extensions.

For such use cases, I recommend that you implement extension callback APIs like BeforeEachCallback as a lambda expression registered via a field.

For example, you can register a local BeforeEachCallback as a lambda expression like this:

class ExampleTests {

    @RegisterExtension
    BeforeEachCallback beforeEach = extensionContext ->
        System.out.println("before: " + extensionContext.getRequiredTestMethod().getName());

    @Test
    void test() {
        /* ... */
    }

}

All 2 comments

Personally, I don't think JUnit Jupiter should supply the ExtensionContext to user-defined lifecycle callback methods, since they are by definition not extensions.

For such use cases, I recommend that you implement extension callback APIs like BeforeEachCallback as a lambda expression registered via a field.

For example, you can register a local BeforeEachCallback as a lambda expression like this:

class ExampleTests {

    @RegisterExtension
    BeforeEachCallback beforeEach = extensionContext ->
        System.out.println("before: " + extensionContext.getRequiredTestMethod().getName());

    @Test
    void test() {
        /* ... */
    }

}

For example, you can register a local BeforeEachCallback as a lambda expression like this:

This definitely makes sense, didn't know we could do it like so as well.
Thanks, in that case I suppose what I'm suggesting isn't required.

Was this page helpful?
0 / 5 - 0 ratings