qxoivwec's avatar

How can I run the same test but with different data?

Hi,

I have an application which handles a lot of phone numbers. Now I want to test an array of items but I don't want to loop over them every time I'm writing the test. I have to repeat this for multiple tests...

Here is a sample code

public function testPhoneNumberLenght()
{
    $phoneNumbers = [
        '0123456789',
        '9876543210',
    ];
    
    foreach ($phoneNumbers as $phoneNumber) {
        $this->assertEquals(10, strlen($phoneNumber);
    }

    // 6 more methods with the same format...
}

I have more of these kind of tests. I don't want to do all the inserts in one place, because that makes it harder to decide what rule failed if the tests fail.

Now when I add a new number I need to add it to 7 methods... How can I improve this?

0 likes
2 replies
bobbybouwmann's avatar
Level 88

Well you can use phpunit data providers for that. Here is an example

/**
 * @dataProvider phoneNumberDataProvider
 */
public function testPhoneNumberLenght($phoneNumber)
{
    $this->assertEquals(10, strlen($phoneNumber);
}

public function phoneNumberDataProvider()
{
    return [
        ['0123456789'],
        ['9876543210'],
    ];
}

This improves your code a lot already. Note that you don't have any loops. Each value will be passed a variable to the method. You can also do this with multiple parameters.

You can find more information here: https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers

6 likes
qxoivwec's avatar

Aah that works perfectly thanks!

1 like

Please or to participate in this conversation.