Skip to main content

Lesson 2 of 8

JUnit 5 - Unit Testing

Testing is a core professional skill. JUnit 5 (Jupiter) is the modern Java testing framework - annotations drive test lifecycle, assertions verify behaviour, and parameterised tests eliminate repetition. Mockito provides mock objects for isolating units under test.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

JUnit 5 + Mockito in Practice

JUnit 5 + Mockito in Practice
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.*;
import org.junit.jupiter.params.provider.*;
import org.mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@DisplayName("LibraryService Tests")
class LibraryServiceTest {

    private BookRepository mockRepo;     // mock - isolates service from DB
    private LibraryService service;

    @BeforeAll   static void setUpClass()  { System.out.println("Once before all tests"); }
    @AfterAll    static void tearDownClass(){ System.out.println("Once after all tests"); }

    @BeforeEach  void setUp() {
        mockRepo = mock(BookRepository.class);
        service  = new LibraryService(mockRepo);
    }

    @AfterEach   void tearDown() { /* cleanup per test */ }

    // ── Basic test ───────────────────────────────────────────────
    @Test
    @DisplayName("should borrow available book successfully")
    void testBorrowAvailableBook() {
        // Arrange
        Book book = new Book("001", "Effective Java", "Bloch", 44.99);
        when(mockRepo.findByIsbn("001")).thenReturn(Optional.of(book));

        // Act
        BorrowRecord record = service.checkout("001", "MBR-001");

        // Assert
        assertNotNull(record);
        assertFalse(book.isAvailable());
        assertEquals("001", record.getBook().getIsbn());
        verify(mockRepo, times(1)).findByIsbn("001");
    }

    @Test
    @DisplayName("should throw BookNotFoundException for unknown ISBN")
    void testBorrowUnknownBook() {
        when(mockRepo.findByIsbn("UNKNOWN")).thenReturn(Optional.empty());

        BookNotFoundException ex = assertThrows(
            BookNotFoundException.class,
            () -> service.checkout("UNKNOWN", "MBR-001")
        );

        assertEquals("UNKNOWN", ex.getIsbn());
    }

    // ── Parameterised tests - one method, multiple inputs ─────────
    @ParameterizedTest
    @ValueSource(strings = {"", " ", "  "})
    @DisplayName("blank ISBN should throw IllegalArgumentException")
    void testBlankIsbn(String isbn) {
        assertThrows(IllegalArgumentException.class,
            () -> service.checkout(isbn, "MBR-001"));
    }

    @ParameterizedTest
    @CsvSource({
        "Clean Code,     39.99, 5.00",
        "Effective Java, 44.99, 5.00",
        "DDIA,           49.99, 10.00"
    })
    @DisplayName("late fee calculation")
    void testLateFee(String title, double price, double expectedFee) {
        Book book = new Book("001", title, "Author", price);
        // ... test late fee logic ...
        assertEquals(expectedFee, book.calculateLateFee(1), 0.001);
    }

    // ── Nested tests - logical grouping ───────────────────────────
    @Nested
    @DisplayName("Search tests")
    class SearchTests {
        @Test
        void testSearchByTitle() { /* ... */ }

        @Test
        void testSearchByAuthor() { /* ... */ }
    }

    // ── Assertions ────────────────────────────────────────────────
    @Test
    void assertionExamples() {
        List<String> list = List.of("A", "B", "C");

        assertEquals(3, list.size());
        assertTrue(list.contains("A"));
        assertFalse(list.isEmpty());
        assertNull(null);
        assertNotNull(list);
        assertIterableEquals(List.of("A","B","C"), list);

        // All assertions even if some fail
        assertAll("list checks",
            () -> assertEquals(3, list.size()),
            () -> assertTrue(list.contains("B")),
            () -> assertFalse(list.contains("Z"))
        );
    }
}

What Makes Good Tests

  • AAA pattern: Arrange (set up data), Act (call the method), Assert (verify outcome).
  • One behaviour per test - not one assertion per test. A test for 'successful checkout' can have multiple assertions about the result.
  • Descriptive names: testBorrowAvailableBookShouldUpdateAvailability - reads like a specification.
  • Fast - unit tests should run in milliseconds. Mock external dependencies (DB, HTTP) with Mockito.
  • Isolated - tests must not depend on each other's execution order. Use @BeforeEach to reset state.
  • Test edge cases: null input, empty list, boundary values (price = 0, price = MAX_VALUE).

Quick Quiz

Tip

Tip

Practice JUnit 5 Unit Testing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for JUnit 5 - Unit Testing

Practice Task

Note

Practice Task - (1) Write a working example of JUnit 5 Unit Testing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with JUnit 5 Unit Testing is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Key Takeaways

  • Testing is a core professional skill.
  • AAA pattern: Arrange (set up data), Act (call the method), Assert (verify outcome).
  • One behaviour per test - not one assertion per test. A test for 'successful checkout' can have multiple assertions about the result.
  • Descriptive names: testBorrowAvailableBookShouldUpdateAvailability - reads like a specification.

Topics in This Module

0/8 done