← Back to Module 3

Unit Testing Fundamentals

What is Unit Testing?

Unit testing is a software testing method where individual components (units) of a program are tested in isolation. The purpose is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software, typically a method or function.

JUnit Basics

Test Class Structure

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

public class CalculatorTest {
    @Test
    void testAddition() {
        Calculator calculator = new Calculator();
        assertEquals(4, calculator.add(2, 2));
    }

    @Test
    void testDivision() {
        Calculator calculator = new Calculator();
        assertEquals(2, calculator.divide(4, 2));
    }
}

Common Assertions

Test Lifecycle

JUnit 5 Annotations

import org.junit.jupiter.api.*;

public class TestLifecycleExample {
    @BeforeAll
    static void setupAll() {
        // Runs once before all tests
    }

    @BeforeEach
    void setup() {
        // Runs before each test
    }

    @Test
    void testMethod() {
        // Test code
    }

    @AfterEach
    void tearDown() {
        // Runs after each test
    }

    @AfterAll
    static void tearDownAll() {
        // Runs once after all tests
    }
}

Test Organization

Test Categories

Test Naming Conventions

// MethodName_Scenario_ExpectedResult
@Test
void calculateTotal_WithValidInputs_ReturnsCorrectSum() {
    // Test code
}

@Test
void processOrder_WithInvalidQuantity_ThrowsIllegalArgumentException() {
    // Test code
}

Test Coverage

Types of Coverage

JaCoCo Configuration

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.7</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Video Content