Skip to main content

Chapter 2: Unit Testing with JUnit 5

Introduction​

JUnit 5 is the standard testing framework for Java. It is the foundation of all your Spring Boot tests. This chapter teaches you how to use it effectively.


🎯 Chapter Objectives​

By the end of this chapter, you will know how to:

  1. ✅ Use JUnit 5 annotations
  2. ✅ Write clear assertions
  3. ✅ Test exceptions
  4. ✅ Create parameterized tests
  5. ✅ Manage the test lifecycle

1. Structure of a Test​

Basic Anatomy​

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {

@Test // ← Indicates a test method
void shouldAddTwoNumbers() {
// Arrange
Calculator calc = new Calculator();

// Act
int result = calc.add(2, 3);

// Assert
assertEquals(5, result);
}
}

Conventions​

class ProductServiceTest {  // ← Name: TestedClass + Test

@Test
void shouldReturnProductById() { // ← Descriptive method
// ...
}

@Test
void shouldThrowExceptionWhenProductNotFound() {
// ...
}
}

2. Main Annotations​

@Test​

import org.junit.jupiter.api.Test;

@Test
void simpleTest() {
assertTrue(1 + 1 == 2);
}

@DisplayName​

@Test
@DisplayName("Should calculate price with 20% VAT")
void shouldCalculatePriceWithVAT() {
double result = priceService.calculateWithVAT(100.0, 0.20);
assertEquals(120.0, result);
}

@Disabled​

@Test
@Disabled("Awaiting bug fix #123")
void brokenTest() {
// This test will be ignored
}

@BeforeEach and @AfterEach​

class ProductServiceTest {

private ProductService productService;

@BeforeEach
void setUp() {
// Executed BEFORE each test
productService = new ProductService();
}

@AfterEach
void tearDown() {
// Executed AFTER each test (cleanup)
productService = null;
}

@Test
void test1() { /* productService is fresh */ }

@Test
void test2() { /* productService is fresh */ }
}

@BeforeAll and @AfterAll​

class DatabaseTest {

@BeforeAll
static void setUpAll() {
// Executed ONCE before all tests
// Must be static!
System.out.println("Global initialization...");
}

@AfterAll
static void tearDownAll() {
// Executed ONCE after all tests
System.out.println("Global cleanup...");
}
}

Execution Order​

@BeforeAll (1 time)
│
├── @BeforeEach
│ └── @Test test1()
│ └── @AfterEach
│
├── @BeforeEach
│ └── @Test test2()
│ └── @AfterEach
│
└── @AfterAll (1 time)

3. Assertions​

Basic Assertions​

import static org.junit.jupiter.api.Assertions.*;

@Test
void demonstrateAssertions() {
// Equality
assertEquals(5, calculator.add(2, 3));
assertEquals("Hello", greeting.getMessage());
assertEquals(3.14, Math.PI, 0.01); // With delta for double

// Booleans
assertTrue(user.isActive());
assertFalse(list.isEmpty());

// Null
assertNull(optionalValue.orElse(null));
assertNotNull(service.findById(1L));

// References
assertSame(expected, actual); // Same object
assertNotSame(obj1, obj2); // Different objects
}

Assertions on Collections​

@Test
void testCollections() {
List<String> fruits = List.of("Apple", "Banana", "Cherry");

// Size
assertEquals(3, fruits.size());

// Content
assertTrue(fruits.contains("Apple"));
assertFalse(fruits.contains("Grape"));

// With AssertJ (more readable)
assertThat(fruits)
.hasSize(3)
.contains("Apple", "Banana")
.doesNotContain("Grape")
.startsWith("Apple")
.endsWith("Cherry");
}

Custom Messages​

@Test
void testWithMessage() {
int age = user.getAge();

assertTrue(age >= 18, "User must be an adult");
assertEquals(25, age, () -> "Expected age was 25 but was " + age);
}

assertAll (Grouped Assertions)​

@Test
void testUserProperties() {
User user = new User("John", "john@email.com", 25);

// All assertions are executed, even if one fails
assertAll("User properties",
() -> assertEquals("John", user.getName()),
() -> assertEquals("john@email.com", user.getEmail()),
() -> assertEquals(25, user.getAge()),
() -> assertTrue(user.isActive())
);
}

4. Testing Exceptions​

assertThrows​

@Test
void shouldThrowExceptionWhenDividingByZero() {
Calculator calc = new Calculator();

// Verify that the exception is thrown
assertThrows(ArithmeticException.class, () -> {
calc.divide(10, 0);
});
}

@Test
void shouldThrowExceptionWithMessage() {
// Capture the exception to verify the message
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> userService.createUser(null)
);

assertEquals("Username cannot be null", exception.getMessage());
}

assertDoesNotThrow​

@Test
void shouldNotThrowException() {
assertDoesNotThrow(() -> {
userService.createUser("validUser");
});
}

5. Parameterized Tests​

@ParameterizedTest with @ValueSource​

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedTest
@ValueSource(strings = {"John", "Jane", "Bob"})
void shouldAcceptValidNames(String name) {
assertTrue(validator.isValidName(name));
}

@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
void shouldBePositive(int number) {
assertTrue(number > 0);
}

@CsvSource​

@ParameterizedTest
@CsvSource({
"1, 1, 2",
"2, 3, 5",
"10, 20, 30",
"-1, 1, 0"
})
void shouldAddNumbers(int a, int b, int expected) {
assertEquals(expected, calculator.add(a, b));
}

@ParameterizedTest
@CsvSource({
"john@email.com, true",
"invalid-email, false",
"test@domain.org, true",
"'', false"
})
void shouldValidateEmail(String email, boolean expected) {
assertEquals(expected, validator.isValidEmail(email));
}

@MethodSource​

@ParameterizedTest
@MethodSource("provideUsers")
void shouldValidateUser(User user, boolean expectedValid) {
assertEquals(expectedValid, validator.isValid(user));
}

static Stream<Arguments> provideUsers() {
return Stream.of(
Arguments.of(new User("John", 25), true),
Arguments.of(new User("", 25), false),
Arguments.of(new User("Jane", -1), false),
Arguments.of(new User("Bob", 18), true)
);
}

@EnumSource​

@ParameterizedTest
@EnumSource(Status.class)
void shouldHandleAllStatuses(Status status) {
assertDoesNotThrow(() -> processor.process(status));
}

@ParameterizedTest
@EnumSource(value = Status.class, names = {"ACTIVE", "PENDING"})
void shouldHandleActiveStatuses(Status status) {
assertTrue(status == Status.ACTIVE || status == Status.PENDING);
}

6. Conditional Tests​

@EnabledOnOs / @DisabledOnOs​

@Test
@EnabledOnOs(OS.WINDOWS)
void windowsOnlyTest() {
// Only runs on Windows
}

@Test
@DisabledOnOs(OS.MAC)
void notOnMacTest() {
// Does not run on Mac
}

@EnabledIfEnvironmentVariable​

@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = "dev")
void onlyInDevEnvironment() {
// Only runs if ENV=dev
}

@EnabledIf​

@Test
@EnabledIf("customCondition")
void conditionalTest() {
// ...
}

boolean customCondition() {
return LocalTime.now().getHour() < 12; // Morning only
}

7. Nested Tests​

@Nested​

class UserServiceTest {

@Nested
@DisplayName("When creating a user")
class CreateUser {

@Test
@DisplayName("should succeed with valid data")
void shouldSucceedWithValidData() {
User user = userService.create("John", "john@email.com");
assertNotNull(user.getId());
}

@Test
@DisplayName("should fail with empty name")
void shouldFailWithEmptyName() {
assertThrows(ValidationException.class,
() -> userService.create("", "john@email.com"));
}
}

@Nested
@DisplayName("When deleting a user")
class DeleteUser {

@Test
@DisplayName("should remove from database")
void shouldRemoveFromDatabase() {
userService.delete(1L);
assertFalse(userService.exists(1L));
}
}
}

Display in IDE​

UserServiceTest
├── When creating a user
│ ├── ✓ should succeed with valid data
│ └── ✓ should fail with empty name
└── When deleting a user
└── ✓ should remove from database

8. Timeouts​

@Timeout​

@Test
@Timeout(5) // Fails if more than 5 seconds
void shouldCompleteQuickly() {
// ...
}

@Test
@Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
void shouldCompleteVeryQuickly() {
// ...
}

assertTimeout​

@Test
void shouldCompleteInTime() {
assertTimeout(Duration.ofSeconds(2), () -> {
// Code that must run in less than 2s
Thread.sleep(1000);
});
}

AssertJ offers a more fluent and readable syntax:

import static org.assertj.core.api.Assertions.*;

@Test
void demonstrateAssertJ() {
// Strings
assertThat("Hello World")
.startsWith("Hello")
.endsWith("World")
.contains("lo Wo")
.hasSize(11);

// Numbers
assertThat(42)
.isPositive()
.isGreaterThan(40)
.isBetween(40, 50);

// Collections
assertThat(List.of("a", "b", "c"))
.hasSize(3)
.contains("a", "b")
.doesNotContain("d")
.containsExactly("a", "b", "c");

// Objects
assertThat(user)
.isNotNull()
.hasFieldOrPropertyWithValue("name", "John")
.extracting(User::getEmail)
.isEqualTo("john@email.com");

// Exceptions
assertThatThrownBy(() -> service.riskyMethod())
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("error");
}

10. Summary​

Key Annotations​

AnnotationDescription
@TestMarks a test method
@BeforeEachBefore each test
@AfterEachAfter each test
@BeforeAllBefore all tests (static)
@AfterAllAfter all tests (static)
@DisplayNameReadable name for the test
@DisabledDisables the test
@ParameterizedTestTest with multiple values
@NestedNested test group

Essential Assertions​

assertEquals(expected, actual);
assertTrue(condition);
assertFalse(condition);
assertNull(value);
assertNotNull(value);
assertThrows(Exception.class, () -> ...);
assertAll("group", () -> ..., () -> ...);

Test Pattern​

@Test
void should_ExpectedBehavior_When_Condition() {
// Arrange
// ...

// Act
// ...

// Assert
// ...
}

🎯 Next Step​

JUnit 5 allows you to write tests, but how do you test a class that depends on other classes? This is where Mockito comes in.

➡️ Chapter 3: Mocking with Mockito


⬅️ Back to Module 9