javajunit5junit5-extension-model

JUnit 5: under what conditions is ExtensionContext.getTestMethod() not available?


I'm working on a JUnit 5 extension where I am using the ExtensionContext.getTestMethod() to extract an annotation from test methods.

Optional<Method> testMethod = context.getTestMethod();

if (testMethod.isPresent()) {
    MyAnnotation annotation = testMethod.get().getAnnotation(MyAnnotation.class);
    //snip...
}

According to the javadoc, the method returns

"an Optional containing the method; never null but potentially empty"

I'm finding this a little confusing. In which situation would the test method be missing?


Solution

  • Let's say I have this extension:

    import org.junit.jupiter.api.extension.*;
    import java.lang.reflect.Method;
    import java.util.Optional;
    
    public class MyExtension implements BeforeAllCallback, BeforeEachCallback {
        @Override
        public void beforeAll(ExtensionContext context) throws Exception {
            Optional<Method> testMethod = context.getTestMethod();
        }
        @Override
        public void beforeEach(ExtensionContext context) {
            Optional<Method> testMethod = context.getTestMethod();
        }
    }
    

    and this test class:

    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    
    @ExtendWith(MyExtension.class)
    class MyTest {
        @Test
        void test1() {
        }
        @Test
        void test2() {
        }
    }
    

    When MyExtension.beforeAll() is executed: which test method should context.getTestMethod() return? MyExtension.beforeAll() is not test-specific, so within beforeAll() the call to context.getTestMethod() cannot return a test method!

    The case is different within MyExtension.beforeEach(): this method is called before each specific test (i.e. once before test1() is executed and once before test2() is executed) and rightfully withn the beforeEach() method the call to context.getTestMethod() returns an optional with the corresponding method object.