Balu
Balu

Reputation: 161

JUnit - method to execute before @BeforeAll and method to execute after @AfterAll

I have multiple JUnit test classes to run with multiple tests in each of them. I have a base test class, which is the parent for all test classes. Is there any way to write methods in base test class that executes before @BeforeAll and after @AfterAll only once for all test classes? Or is there any interface that can be implemented or any class that can be extended to solve this problem?

BaseJUnitTest.class

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
public class BaseJUnitTest {

    // method to execute before all JUnit test classes

    @BeforeAll
    public static void beforeAll() throws Exception {

    }

    @AfterAll
    public static void afterAll() throws Exception {

    }

    @BeforeEach
    public void beaforeEachTest() {

    }

    @AfterEach
    public void afterEachTest() {

    }

    // method to execute after all JUnit test classes
}

SampleTest.class

public class SampleTest extends BaseJUnitTest {

@Test
public void test1() {
    System.out.println("SampleTest test1");
}
}

Note: I'm using JUnit 5, although in this scenario I hope it doesn't matter much about JUnit 4 or 5

Upvotes: 0

Views: 2392

Answers (2)

Dev Amitabh
Dev Amitabh

Reputation: 185

First answer by Salim is the way to go. To answer your other query in comment, you will need to register classes that are part of your suit using @SuiteClasses annotation.

EDIT:

To register test cases the other way round, Reflection is the way to go. You'll need to implement ClassFinder, TestCaseLoader and TestAll classes. You can define the TestCaseLoader for each project while TestAll could be part of the ditributable jar. A detailed example can be found here: https://www.javaworld.com/article/2076265/testing-debugging/junit-best-practices.html?page=2

Upvotes: 0

Salim
Salim

Reputation: 2178

I think you need a "test suite" instead of a base test class. This suite will contain your test cases. On this test suite class use @Beforeclass and @Afterclass to include work which needs to be done before or after all tests present in the suite.

Here is a detail answer Before and After Suite execution hook in jUnit 4.x

Upvotes: 2

Related Questions