JUnit is a testing library used to test the System Integration(full system after deployment) and Unit testing(Class or method testing).
@BeforeAll and @AfterAll requires the methods to be of type static.
package com.brains.junit;
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.jupiter.api.Test;
class MyBeforeAfterTest {
@BeforeAll
static void beforeAll() {
System.out.println("beforeAll");
}
@BeforeEach
void beforeEach() {
System.out.println("beforeEach");
}
@Test
void test1() {
System.out.println("test1");
}
@Test
void test2() {
System.out.println("test2");
}
@Test
void test3() {
System.out.println("test3");
}
@AfterEach
void afterEach() {
System.out.println("afterEach");
}
@AfterAll
static void afterAll() {
System.out.println("afterAll");
}
}
Console output
beforeAll
beforeEach
test1
afterEach
beforeEach
test2
afterEach
beforeEach
test3
afterEach
afterAll
Create MyMath.java class and add a calculate method, we would be applying the test cases on this method.
package com.brains.junit;
public class MyMath {
public int calculateSum(int[] numbers) {
int total = 0;
for(int i:numbers) {
total += i;
}
return total;
}
}
Create the Test class in a separate package and use the existing Classes to test it’s functionality.
package com.brains.junit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class MyMathTest {
private MyMath math = new MyMath();
List todos = Arrays.asList("AWS", "DevOps", "Java");
// test sum {1,2,3} -> 6
@Test
void calculate_sum_three_member() {
assertEquals(6, math.calculateSum(new int[] {1,2,3}));
}
// test sum {} -> 0
@Test
void calculate_sum_zero_lengthArray() {
assertEquals(0, math.calculateSum(new int[] {}));
}
@Test
void test() {
assertEquals(true, todos.contains("AWS"));
assertEquals(3, todos.size());
}
}
On running the JUnit Test case, if all the tests are passed, it would show green bar as shown below.
