Junit - run set up method once
I set up a class with a couple of tests and rather than using @Before
I would like to have a setup method that executes only once before all tests. Is that possible with Junit 4.8?
Although I agree with @assylias that using @BeforeClass
is a classic solution it is not always convenient. The method annotated with @BeforeClass
must be static. It is very inconvenient for some tests that need instance of test case. For example Spring based tests that use @Autowired
to work with services defined in spring context.
In this case I personally use regular setUp()
method annotated with @Before
annotation and manage my custom static
(!) boolean
flag:
private static boolean setUpIsDone = false;
.....
@Before
public void setUp() {
if (setUpIsDone) {
return;
}
// do the setup
setUpIsDone = true;
}
You can use the BeforeClass
annotation:
@BeforeClass
public static void setUpClass() {
//executed only once, before the first test
}
JUnit 5 now has a @BeforeAll annotation:
Denotes that the annotated method should be executed before all @Test methods in the current class or class hierarchy; analogous to JUnit 4’s @BeforeClass. Such methods must be static.
The lifecycle annotations of JUnit 5 seem to have finally gotten it right! You can guess which annotations available without even looking (e.g. @BeforeEach @AfterAll)
When setUp()
is in a superclass of the test class (e.g. AbstractTestBase
below), the accepted answer can be modified as follows:
public abstract class AbstractTestBase {
private static Class<? extends AbstractTestBase> testClass;
.....
public void setUp() {
if (this.getClass().equals(testClass)) {
return;
}
// do the setup - once per concrete test class
.....
testClass = this.getClass();
}
}
This should work for a single non-static setUp()
method but I'm unable to produce an equivalent for tearDown()
without straying into a world of complex reflection... Bounty points to anyone who can!