Home > Software engineering >  JUnit 5: execute code once before multiple tests
JUnit 5: execute code once before multiple tests

Time:10-27

I'm working on a project which uses Quarkus to spin up a few REST endpoints. I have multiple integration tests which run with different test profiles or completely without a test profile. Heres an example:

@QuarkusTest
@Tag("integration")
@TestProfile(SomeProfile::class)
class IntegrationTestWithSomeProfile {
    @Test 
    fun someTest() { ... }
}

@QuarkusTest
@Tag("integration")
class IntegrationTestWithoutProfile {
    @Test 
    fun someTest() { ... }
}

Now I would like to execute a piece of code before the first test runs (or after the last test has finished). The problem is that @BeforeAll can only be used per class and I can't use Quarkus' start and stop events since Quarkus is started and shutdown multiple times - once for each different test profile.

Is there any hook (or hack - i don't mind dirty stuff as long as it works) which I could use, which would execute only once at the very beginning?

CodePudding user response:

You can try @QuarkusTestResource with a class implementing QuarkusTestResourceLifecycleManager. This can be used to start/stop services on the classes you want.

See: https://quarkus.io/guides/getting-started-testing#quarkus-test-resource

CodePudding user response:

I finally found the solution I need. It's called TestExecutionListener. I went the route with adding a file called org.junit.platform.launcher.TestExecutionListener in resources/META-INF/services. Inside this file I've put the fqcn of my class implementing the TestExecutionListener interface.

In there I can then override testPlanExecutionStarted() and testPlanExecutionFinished(). With this, it doesn't matter how many TestProfiles we use and how many times Quarkus is started and stopped. The TestExecutionListener runs only once.

  • Related