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:
- Arrange: Prepare the data (Get the bolt).
- Act: Run the code (Stress-test the bolt).
- 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?
- Confidence: You can change code without fear of breaking other parts.
- Documentation: Tests show other developers exactly how your code is supposed to be used.
- Speed: Running 1,000 tests takes 2 seconds. Manually clicking through your website to test one feature takes 10 minutes.
🥅 Module 1 Review
- Unit Test: Testing one small piece of code in isolation.
- JUnit 5: The standard tool for running tests in Java.
- AAA Pattern: Arrange, Act, Assert.
- @Test: The label that tells Java: “This is a test, not a real part of the app.”