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

  • assertEquals(expected, actual) - Checks if two values are equal
  • assertTrue(condition) - Verifies a condition is true
  • assertFalse(condition) - Verifies a condition is false
  • assertNull(object) - Checks if an object is null
  • assertNotNull(object) - Checks if an object is not null
  • assertThrows(expectedType, executable) - Verifies that an exception is thrown

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

  • Happy Path Tests: Test normal operation with valid inputs
  • Edge Cases: Test boundary conditions and limits
  • Error Cases: Test error handling and invalid inputs
  • Integration Tests: Test interaction between components

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

  • Line Coverage: Percentage of code lines executed
  • Branch Coverage: Percentage of code branches executed
  • Method Coverage: Percentage of methods called
  • Class Coverage: Percentage of classes tested

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