0

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

Balu
  • 141
  • 3
  • 17

2 Answers2

2

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

Salim
  • 2,046
  • 12
  • 13
  • I have gone through the above article. I am designing a test utility jar, ``BaseJUnitTest`` do some reporting, logging etc setup which tester does not need to bother about. so I need to pack my `BaseJUnitTest` as part of the jar file, in this scenario is there any way to provide List of Test classes to `BaseJUnitTest`? – Balu Dec 11 '17 at 05:54
0

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

Dev Amitabh
  • 185
  • 1
  • 4
  • I am packing Suite class in the jar (a test utility) and sharing it across projects for writing unit tests, so I don't have clue what all tests need to be included. – Balu Dec 11 '17 at 13:35