Skip to content

Module 1: Unit Testing with JUnit 5 (Testing the Bolt)

📚 Module 1: Unit Testing with JUnit 5

Focus: Moving from “Running the whole app” to “Testing one part.”

A Senior Developer never says: “I think this code works.” They say: “I have tests that PROVE this code works.” We use JUnit 5 to test small, individual pieces of code (Units).


🏗️ Step 1: What is a Unit? (The “Bolt”)

A unit is the smallest piece of code possible—usually a single method.

🧩 The Analogy: Building a Plane

  • You don’t build a whole plane and then try to fly it to see if it works. (That’s dangerous!).
  • You test every Bolt separately.
  • You test every Engine separately.
  • If every bolt and engine works, the plane is much more likely to stay in the air.

🏗️ Step 2: The Three Parts of a Test (AAA)

Every professional test follows the AAA pattern:

  1. Arrange: Prepare the data (Get the bolt).
  2. Act: Run the code (Stress-test the bolt).
  3. Assert: Check the result (Did the bolt break?).

In Code:

@Test
public void shouldCalculateTotalPrice() {
    // 1. ARRANGE
    Calculator calc = new Calculator();
    
    // 2. ACT
    int result = calc.add(10, 20);
    
    // 3. ASSERT
    assertEquals(30, result);
}

🏗️ Step 3: Why do we test?

  1. Confidence: You can change code without fear of breaking other parts.
  2. Documentation: Tests show other developers exactly how your code is supposed to be used.
  3. Speed: Running 1,000 tests takes 2 seconds. Manually clicking through your website to test one feature takes 10 minutes.

🥅 Module 1 Review

  1. Unit Test: Testing one small piece of code in isolation.
  2. JUnit 5: The standard tool for running tests in Java.
  3. AAA Pattern: Arrange, Act, Assert.
  4. @Test: The label that tells Java: “This is a test, not a real part of the app.”