Java
Module 33: Java Testing (JUnit & Mockito)Beginner22 min read

Unit Testing with JUnit 5 & Mockito

Structure reliable unit tests using JUnit 5 lifecycle annotations, assertions, and Mockito mocks for isolated business logic testing.

Key Takeaways & Core Concepts
  • @BeforeAll / @AfterAll: Static setup/teardown once per test class.
  • @BeforeEach / @AfterEach: Fresh setup before/after every @Test method so tests never share mutable state.
  • @ParameterizedTest with @CsvSource / @ValueSource: Runs the same test logic across dozens of edge-case inputs cleanly.
  • Assertions: assertEquals, assertNotNull, assertThrows(IllegalArgumentException.class, () -> ...), assertAll.

Why Automated Testing Matters

Automated unit and integration tests give engineering teams confidence to refactor and ship rapidly without breaking existing behavior.

Arrange-Act-Assert Unit Test Pattern
1public class Main {
2 static int add(int a, int b) { return a + b; }
3
4 public static void main(String[] args) {
5 // Arrange
6 int x = 15, y = 25;
7 // Act
8 int result = add(x, y);
9 // Assert
10 if (result != 40) throw new AssertionError("Expected 40, got " + result);
11 System.out.println("Test Passed: add(15, 25) == 40");
12 }
13}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: Separating Arrange, Act, and Assert keeps tests readable and easy to debug.

JUnit 5 Architecture & Lifecycle

  • @BeforeAll / @AfterAll: Static setup/teardown once per test class.
  • @BeforeEach / @AfterEach: Fresh setup before/after every @Test method so tests never share mutable state.
  • @ParameterizedTest with @CsvSource / @ValueSource: Runs the same test logic across dozens of edge-case inputs cleanly.
  • Assertions: assertEquals, assertNotNull, assertThrows(IllegalArgumentException.class, () -> ...), assertAll.

Isolating Dependencies with Mockito

When testing OrderService, you don't want to hit a real payment gateway or database. Use @Mock for PaymentGateway and @InjectMocks for OrderService, stub behavior with when(...).thenReturn(...), and verify interactions with verify(...).

Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)