Back to Repositories

Testing Z Algorithm String Pattern Matching in williamfiset/Algorithms

This test suite validates the Z Algorithm implementation for string pattern matching in Java. It comprehensively tests various string patterns and edge cases to ensure correct Z-array computation for string matching applications.

Test Coverage Overview

The test suite provides comprehensive coverage of the Z Algorithm implementation:

  • Edge case handling for null and empty inputs
  • Single character repetition patterns
  • Distinct character sequences
  • Complex repeating pattern scenarios
  • Various string lengths and pattern combinations

Implementation Analysis

The testing approach utilizes JUnit Jupiter framework with Google Truth assertions for enhanced readability and precise verification. Each test case systematically validates different string pattern scenarios, employing the @BeforeEach setup for consistent test initialization.

The implementation follows AAA (Arrange-Act-Assert) pattern with clear test method naming conventions.

Technical Details

Testing Infrastructure:

  • JUnit Jupiter test framework
  • Google Truth assertion library
  • Java-based test implementation
  • BeforeEach test lifecycle management
  • Isolated test methods for specific scenarios

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Descriptive test method names following ‘should’ pattern
  • Proper test isolation and setup
  • Comprehensive edge case coverage
  • Clear assertion statements
  • Systematic test organization by scenario type

williamfiset/algorithms

src/test/java/com/williamfiset/algorithms/strings/ZAlgorithmTest.java

            
package com.williamfiset.algorithms.strings;

import static com.google.common.truth.Truth.assertThat;

import org.junit.jupiter.api.*;

public class ZAlgorithmTest {
  private ZAlgorithm underTest;

  @BeforeEach
  public void setup() {
    underTest = new ZAlgorithm();
  }

  @Test
  public void shouldReturnEmptyArrayOnNullOrEmptyInput() {
    assertThat(underTest.calculateZ(null)).isEmpty();
    assertThat(underTest.calculateZ("")).isEmpty();
  }

  @Test
  public void textContainsASingleCharacterRepeated() {
    assertThat(underTest.calculateZ("aaaaaaa")).isEqualTo(new int[] {7, 6, 5, 4, 3, 2, 1});
    assertThat(underTest.calculateZ("bbbbbbbb")).isEqualTo(new int[] {8, 7, 6, 5, 4, 3, 2, 1});
  }

  @Test
  public void textContainsAllDistinctCharacters() {
    assertThat(underTest.calculateZ("abcdefgh")).isEqualTo(new int[] {8, 0, 0, 0, 0, 0, 0, 0});
  }

  @Test
  public void textContainsRepeatedPattern() {
    assertThat(underTest.calculateZ("abababab")).isEqualTo(new int[] {8, 0, 6, 0, 4, 0, 2, 0});
    assertThat(underTest.calculateZ("ababababa")).isEqualTo(new int[] {9, 0, 7, 0, 5, 0, 3, 0, 1});
    assertThat(underTest.calculateZ("abcabcabca"))
        .isEqualTo(new int[] {10, 0, 0, 7, 0, 0, 4, 0, 0, 1});
  }
}