I would like to write a JUnit 5 extension that can register additional dynamic tests during execution. These would ideally appear as children of the executing test method or class.
I've looked at the ExecutionContext
provided to extension callback instances and it doesn't seem that it has any hooks to allow this.
Is there any other mechanism that an executing test could use to register additional tests?
From the comment I can see that I wasn't 100% clear about what I was after.
@TestFactory
and dynamic tests are close to what I am after, but not quite there. They look something like this:
@TestFactory
Iterator<DynamicTest> dynamicTestsFromIterator() {
return Arrays.asList(
dynamicTest("5th dynamic test", () -> assertTrue(isPalindrome("madam"))),
dynamicTest("6th dynamic test", () -> assertEquals(4, calculator.multiply(2, 2)))
).iterator();
}
I was hoping to be able to avoid the boilerplate code and have something that looks like this:
@Test
public void dynamicTestsFromIterator() {
registerDynamicTest("5th dynamic test", () -> assertTrue(isPalindrome("madam")));
registerDynamicTest("6th dynamic test", () -> assertEquals(4, calculator.multiply(2, 2)));
}
In this way, in the application that I had in mind, I could easily retro-fit dynamic tests into my existing suite of tests without having to do a lot of refactoring to use @TestFactory
. I think the code also is a bit neater and more readable without that extra boilerplate.
Thank you to @Sormuras for the link to the doc, which prompted me to re-read the section on dynamic tests (https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-test-examples). The answer is there:
As of JUnit Jupiter 5.4.2, dynamic tests must always be created by factory methods; however, this might be complemented by a registration facility in a later release.
So the registration facility that I am after does not exist in Jupiter as yet. I might be able to use @TestFactory
as a workaround for my purposes though.