Labs ICT
โญ Pro Login

Unit Testing Deep Dive

Advanced unit testing techniques, mocking, and test coverage.

Unit Testing Deep Dive

Unit testing is the practice of testing individual components (methods, classes) in isolation. It is the foundation of the testing pyramid and the most effective way to catch defects early.

The Testing Pyramid


                    /\
                   /  \
                  / UI \          Few, Slow, Expensive
                 / Tests\
                /--------\
               /Integration\
              /   Tests     \    Moderate
             /----------------\
            /    Unit Tests     \   Many, Fast, Cheap
           /______________________\

  +---------------------------------------------------------+
  |   Unit Tests:    70% - Test individual methods          |
  |   Integration:   20% - Test module interactions         |
  |   UI Tests:      10% - Test user-facing behavior        |
  +---------------------------------------------------------+

Writing Good Unit Tests


  // Arrange, Act, Assert (AAA Pattern)
  @Test
  public void testDepositIncreasesBalance() {
      // Arrange
      BankAccount account = new BankAccount(100.0);

      // Act
      account.deposit(50.0);

      // Assert
      assertEquals(150.0, account.getBalance(), 0.001);
  }

  @Test
  public void testDepositWithNegativeAmountThrows() {
      // Arrange
      BankAccount account = new BankAccount(100.0);

      // Act & Assert
      assertThrows(IllegalArgumentException.class, () -> {
          account.deposit(-50.0);
      });
  }

Test Coverage Goals

  • Statement Coverage: Every line of code executed at least once
  • Branch Coverage: Every if/else path taken at least once
  • Path Coverage: Every possible execution path tested
  • Target 80-90% code coverage for most projects

Key Takeaways

  • Unit tests are fast, focused, and provide immediate feedback
  • Follow the AAA pattern: Arrange, Act, Assert
  • Test both happy paths and edge cases
  • High test coverage gives confidence in code correctness

๐Ÿงช Quick Quiz

Which testing level focuses on individual functions or methods?