JUnit Basics
JUnit 5 testing framework essentials for Java.
Basic Test
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
void testAddition() {
assertEquals(4, 2 + 2);
}
@Test
void testSubtraction() {
assertEquals(0, 2 - 2);
}
}
Assertions
Equality
assertEquals(expected, actual);
assertEquals(expected, actual, "message");
Boolean
assertTrue(condition);
assertFalse(condition);
Null checks
assertNull(object);
assertNotNull(object);
Same/Not same
assertSame(expected, actual);
assertNotSame(expected, actual);
Array equality
assertArrayEquals(expectedArray, actualArray);
Lifecycle Annotations
import org.junit.jupiter.api.*;
public class TestLifecycle {
@BeforeAll
static void initAll() {
// Runs once before all tests
}
@BeforeEach
void init() {
// Runs before each test
}
@AfterEach
void tearDown() {
// Runs after each test
}
@AfterAll
static void tearDownAll() {
// Runs once after all tests
}
}
Advanced Features
Disable test
@Disabled("Not implemented yet")
@Test
void testFeature() {}
Timeout
@Test
@Timeout(5)
void testWithTimeout() {}
Exception testing
@Test
void testException() {
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException();
});
}
Parameterized
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testNumbers(int number) {
assertTrue(number > 0);
}