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?
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.