-
Identify what to test. Determine which method and country code the user wants covered. Check src/Validator.php $formats array to confirm the country code exists and note its format strings. Check $zipNames if testing getZipName().
- Verify the country code is present in
$formats before writing the test.
-
Name the test method. Follow the pattern test{CountryAdjective}Code() for isValid() country tests (e.g., testCanadianCode, testJapaneseCode). For other methods use descriptive names: testZipName, testGetFormats, testHasCountry, testInvalidCountryCode, testGetFormatsWithInvalidCountryCode.
- Verify no method with the same name already exists in the file before adding.
-
Write a valid-code assertion. For isValid() tests, assert at least one real postal code that matches the country's format:
public function testCanadianCode()
{
$validator = new Validator();
$this->assertTrue($validator->isValid('CA', 'K1A 0B1'));
}
-
Add a false assertion when the format is strict. If the format requires a space (e.g., '@#@ #@#', '### ##') include an assertFalse for the no-space version and a assertTrue with $ignoreSpaces = true:
$this->assertFalse($validator->isValid('CA', 'K1A0B1'));
$this->assertTrue($validator->isValid('CA', 'K1A0B1', true));
- Only add this when the format string contains a literal space character.
-
Test getFormats(). Assert the exact array from $formats:
public function testGetFormats()
{
$validator = new Validator();
$this->assertEquals(['@#@ #@#'], $validator->getFormats('CA'));
}
-
Test getZipName(). Check both a country in $zipNames and the fallback default:
public function testZipName()
{
$validator = new Validator();
$this->assertEquals('ZIP code', $validator->getZipName('US'));
$this->assertEquals('Postal Code', $validator->getZipName('invalid_country_code'));
}
-
Test hasCountry(). Assert true for a known code and false for an invalid one:
public function testHasCountry()
{
$validator = new Validator();
$this->assertTrue($validator->hasCountry('US'));
$this->assertFalse($validator->hasCountry('invalid_country_code'));
}
-
Test ValidationException throwing. Use @expectedException docblock — one method for isValid(), one for getFormats():
public function testInvalidCountryCode()
{
$validator = new Validator();
$validator->isValid('XXXXXX', 'YYYYYY');
}
public function testGetFormatsWithInvalidCountryCode()
{
$validator = new Validator();
$validator->getFormats('invalid_country_code');
}
-
Insert new methods before the closing } of the class. Append; do not reorder existing tests.
-
Run tests to confirm green:
vendor/bin/phpunit tests/ -v