It is possible to run a method only once for the entire test class before any of the tests are executed, and prior to any @Before method(s). “Once only setup” are useful for starting servers, opening communications, etc. It's time-consuming to close and re-open resources for each test.
Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .
The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With