Artur
Artur

Reputation: 793

JUnit 5. How to run code before / after all tests without extension

Before all tests, it's needed to insert data into database.
After all tests, it's needed to remove all data from database.

In TestNG it's possible to do such stuff using @BeforeSuite and @AfterSuite.
How to do such stuff in JUnit 5?

In Junit 5 @BeforeAll annotation marks a method to run before all tests in a class.
@AfterAll annotation marks a method to run after all tests in a class.

I found following solution on stackoverflow:
https://stackoverflow.com/a/51556718/6643395

But:

Upvotes: 1

Views: 1639

Answers (1)

rü-
rü-

Reputation: 2312

Maybe it was added later, but the answer you referenced actually includes a hook to run code after all tests of all classes have finished, by using a CloseableResource. This is exactly what you're looking for.

And you can also annotate your super class with the extension, as @ExtendWith is inherited. If you use your custom meta-annotation, you'll have to annotate that as @Inherited, too. In this way, you can do the stuff in one place.

BTW: it's often even easier to not inherit from common super classes but to use extensions everywhere instead.

Upvotes: 1

Related Questions