In this post under JUnit, I will explain with example the purpose of “beforeAll” and “afterAll” annotations.
In the previous post under JUnit, I covered about “beforeEach” and “afterEach” annotation.
Similarly to “beforeEach” and “afterEach”, “beforeAll” and “afterAll” is applied to methods.
But methods annotated with “beforeEach” and “afterEach” annotations are executed before and after each test execution.
Whereas in case of methods annotated with “beforeAll” and “afterAll” annotations are executed exactly once before and after all test execution.
For our example lets take an example of “BankAccount” service as shown below
package package16;
public class BankAccount {
private long amount;
public BankAccount(long amount) {
this.amount = amount;
}
public void debit(long amount) {
this.amount = this.amount - amount;
}
public void credit(long amount) {
this.amount = this.amount + amount;
}
public long getAmount() {
return this.amount;
}
}
Below is the test class
Test class
package package16;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BankAccountTest {
@BeforeAll
public static void beforeAll() {
System.out.println("Executing Before all test methods");
}
@Test
public void testDebit() {
System.out.println("Executing testDebit");
BankAccount bankAccount = new BankAccount(1000);
bankAccount.debit(50);
assertEquals(Long.valueOf(950), bankAccount.getAmount());
}
@Test
public void testCredit() {
System.out.println("Executing testCredit");
BankAccount bankAccount = new BankAccount(10000);
bankAccount.credit(50);
assertEquals(Long.valueOf(10050), bankAccount.getAmount());
}
@AfterAll
public static void afterAll() {
System.out.println("Executing After all test methods");
}
}
The output will be
Output
Executing Before all test methods
Executing testDebit
Executing testCredit
Executing After all test methods
Please note: the method annotated with “beforeAll” and “afterAll” annotations must be static void methods.