Search code examples
javamavenjunit5

Run code in junit 5 after all tests in all test classes terminated


For test evidence I would like to archive all tests artifacts (like eg Server calls and responses) that I wrote into a specific directory. I got the method to zip the directory, but I din't find a suitable place to execute it.

The test life cycle callbacks don't seem to be the right place since @AfterAll is called after each test class, but the archive should be generated after all tests in all test classes terminated.

After reading posts like How to code once before and once after all junit5 tests have executed in a module? there seems to be little hope to execute the call from within junit.

I found an extension TestLauncher, but after reading the scarce documentation this rather seems to be used to start the tests from the outside. Especially the SummaryGeneratingListener sounds useful for extending after reading https://www.codota.com/web/assistant/code/rs/5c7c89fd2f7dae0001637b13#L33 but if I put this code in the tree under mavens src/test I don't see how only this launcher will be called and not all the single tests as well...

Since the code will eventually run in a maven build where the archiving really matters I thought maybe there is a possibility to run it after target test. But I understood that maven stops if there at least a certain amount of errors in the test target and then the following code will not be executed. But it's the error situation where the evidence will be most useful.

Did anybody try something similar?

Thanks for sharing thoughts, ideas and experience


Solution

  • In general there are several solutions for the problem.

    • You could define the beforeAll/afterAll on a parent class from which all of your tests inherit. Another option would be to try to define the beforeAll/afterAll on an interface (I'm not 100% sure if this works; I would say it should). In beforeAll you could initialize your setup and in the afterEachCallBack your can collect all the data you need for a single test. So this is called after each test.

    • You could implement an extension which uses the callbacks of JUnit which are BeforeAllCallback and AfterAllCallBack which could handle that. Based on what you exactly need you may need to implement beforeEachCallBack/afterEachCallBack as well.

    • Another option would be to use the Test Execution listener where you can use testPlanExecutionStarted and testPlanExecutionFinished which you should implemented to record and get all you need.

    I've made an example project which shows the usage of the JUnit Jupiter listener.