Unit Testing

What Is Unit Testing?

Unit testing is the practice of testing the smallest testable parts of a software system, such as individual functions, methods, or classes, to verify that each works correctly in isolation.

A unit is typically a single piece of logic with a clear input and output. Unit tests confirm that this logic behaves as expected under normal conditions, edge cases, and error scenarios.

    Why It MattersWho Performs ItWhen It Occurs
    • Detects defects early, when they are cheapest to fix
    • Improves code quality and design
    • Makes refactoring safer
    • Provides fast feedback during development
    • Reduces defects that reach later testing stages
    • Software Developers
    • Sometimes supported by automated testing as part of CI/CD pipelines
    • During the development (coding) phase
    • Before integration, system, or user acceptance testing
    • Re-run whenever code changes are made

    Typical Unit Testing Techniques

      1. White-Box Testing
        • Tests are designed with full knowledge of the internal code structure.
        • Purpose: Ensure all logical paths and conditions are exercised.
        • Techniques include:
          • Statement coverage
          • Branch coverage
          • Path coverage
      2. Equivalence Partitioning
        • Input data is divided into valid and invalid groups (partitions), and one value from each group is tested.
        • Purpose: Reduce the number of test cases while maintaining coverage.
      3. Boundary Value Analysis
        • Focuses on values at the edges of acceptable input ranges.
        • Purpose: Catch defects that often occur at limits (e.g., minimums and maximums).
      4. Error Handling & Exception Testing
        • Verifies how the unit behaves when invalid data, exceptions, or failures occur.
        • Purpose: Ensure graceful handling of errors and predictable system behavior.
      5. Mocking and Stubbing
        • External dependencies (databases, APIs, services) are replaced with simulated objects.
        • Purpose: Allow the unit to be tested in isolation, without relying on other components.

      Key Takeaways

      1. Unit testing ensures individual pieces of code work correctly before they are combined into a complete system.
      2. Strong unit testing dramatically reduces downstream defects and creates a stable foundation for all other testing activities.