Homewrecker
Homewrecker

Reputation: 1106

Junit 4 execution order vs Junit 5

I am seeing some unwanted behaviour using Junit 5. I have the following structure:

website
    config
        BaseTest.java
    tests
        package a
            Test 1
            Test 2
        package b
            Test 3
            Test 4

BaseTest contains an @BeforeAll with some one-time setup and an @BeforeEach and @AfterEach to setup and teardown some data before and after each test. Each test extends from BaseTest.

The way I am used to with Junit 4 is that the @BeforeAll in BaseTest is only run once when executing all the tests in all the packages at once. However, with Junit 5 it seems that the @BeforeAll is repeated when a test from another package is run. To clarify, I get something like this:

BeforeAll
    BeforeEach
        Package 1 Test 1
    AfterEach
    BeforeEach
        Package 1 Test 2
    AfterEach
AfterAll
BeforeAll
    BeforeEach
        Package 2 Test 1
    AfterEach
    BeforeEach
        Package 2 Test 2
    AfterEach
AfterAll

Thanks in advance! Regards

Upvotes: 4

Views: 679

Answers (2)

Homewrecker
Homewrecker

Reputation: 1106

I managed to fix it by overriding the BeforeAllCallback and registering it with my BaseTest like so:

JunitExtensions.class

import com.codeborne.selenide.Configuration;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class JunitExtensions implements BeforeAllCallback {

    @Override
    public void beforeAll(ExtensionContext extensionContext) throws Exception {
        //Code that needs to be ran before all tests goes here
    }
}

Basetest.java

@ExtendWith(JunitExtensions.class)
public class BaseTest {
        //code goes here
    }
}

Upvotes: 0

Sam Brannen
Sam Brannen

Reputation: 31197

The way I am used to with Junit 4 is that the @BeforeAll in BaseTest is only run once when executing all the tests in all the packages at once.

That is incorrect.

I recreated your example using JUnit 4 annotations, and the following is the result:

BeforeClass
    Before
        Package 1 Test 1
    After
    Before
        Package 1 Test 2
    After
AfterClass
BeforeClass
    Before
        Package 2 Test 1
    After
    Before
        Package 2 Test 2
    After
AfterClass

Thus, the behavior in question is identical in JUnit 4 and JUnit Jupiter.

Upvotes: 4

Related Questions