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?
Let's say I have this extension:
and this test class:
When
MyExtension.beforeAll()is executed: which test method shouldcontext.getTestMethod()return?MyExtension.beforeAll()is not test-specific, so withinbeforeAll()the call tocontext.getTestMethod()cannot return a test method!The case is different within
MyExtension.beforeEach(): this method is called before each specific test (i.e. once beforetest1()is executed and once beforetest2()is executed) and rightfully withn thebeforeEach()method the call tocontext.getTestMethod()returns an optional with the corresponding method object.