mercredi 20 septembre 2017

Testing constructors with multiple arguments using PHPUnit

Given the following Value object (no publicly accessible setters):

class Address
{
    public function __construct(string $addressLine1, string $addressLine2 = null, string $town, string $county, PostcodeInterface $postcode)
    {
        if (!$this->validateAddressLine($addressLine1)) {
            throw new \InvalidArgumentException(...);
        }
        $this->addressLine1 = $this->normaliseAddressLine($addressLine1);
        ...
    }

    private function validateAddressLine(string $addressLine)
    {
        ...
    }

    private function normaliseAddressLine(string $addressLine)
    {
        ...
    }
}

I have the following test class:

class AddressTest extends PHPUnit\Framework\TestCase
{
    public function invalidConstructorArgs()
    {
        return [
            ['1/1 Greenbank Road', '%$', 'city', 'county', new Postcode('123FX')]
        ];
    }

    /**
     * @test
     * @dataProvider invalidConstructorArgs
     */
    public function constructor_with_invalid_args_throws_exception($addressLine1, $addressLine2, $town, $county, $postcode)
    {
        $this->expectedException(\InvalidArgumentException::class);
        $address = new Address($addressLine1, $addressLine2, $town, $county, $postcode);
    }
}

As you can see I am currently using a DataProvider to supply my unit test with data. Doing so results in a large array of values to be tested which are all written manually.

Is there something in PHPUnit I should be making use of that I have overlooked for this type of scenario?

Aucun commentaire:

Enregistrer un commentaire