0

I'm using DynamicNode very successfully in a framework that dynamically generates tests and executes them.

Now I have a need to execute some code after all DynamicNode collections have executed. This can mean that I have a single JUnit5 class with multiple methods that return Iterable<DynamicNode>, but I want to run something only after all the test methods have completed.

Is there a way to do this automatically ?

EDIT: ideally I would like my framework to inject the code to be executed automatically, without the user needing to add a @AfterAll annotation on a method and write some extra code.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248

1 Answers1

2

Each method that is annotated with @TestFactory takes part in the default lifecycle. That means in your case an @AfterAll annotated method should do the trick.

@AfterAll

Denotes that the annotated method should be executed after all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @AfterClass. Such methods are inherited (unless they are hidden or overridden) and must be static (unless the "per-class" test instance lifecycle is used).

Copied from https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

Sormuras
  • 8,491
  • 1
  • 38
  • 64
  • thanks, I edited my question - is there a way to not require the user to add the `@AfterAll` annotation and write code, maybe there is a way for my `DynamicNode` iterator implementation to tell JUnit that some code has to be executed on shutdown ? – Peter Thomas Mar 08 '20 at 06:06
  • Do you have already an extension that your users apply to a test class? Perhaps https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/extension/AfterAllCallback.html is the right tool then. – Sormuras Mar 08 '20 at 06:22
  • no, this is purely `DynamicNode` based. finally I am going with a very dirty JVM shutdown hook approach, but for local unit testing, I hope this is fine: https://github.com/intuit/karate/blob/develop/karate-junit5/src/main/java/com/intuit/karate/junit5/Karate.java – Peter Thomas Mar 08 '20 at 06:47