Keeping (large) data providers organized in PHPUnit

Erik Booij on February 17, 2019

When using data providers for you PHPUnit tests, it's easy to get carried away and add loads of different test cases with subtle differences in p... [Read Full]
markdown guide
 

Data providers are even better organized with yield instead of return array. It also gives you the ability to re-use array in items.

I switched with Rector in all my tests and I cannot go back :)

 

Hi Tomáš, I must admit that I haven't given generators in data providers much thought yet, so it's at least a welcome new perspective.

As of yet, I don't see any real clear advantages of generators over plain old arrays though. Syntax is a bit different and one might argue that a yield looks a bit cleaner, whereas one might also argue that more developers are likely to be familiar with arrays than generators, which might help collaboration. Am I missing some benefits?

Thanks for the Rector hint. I hadn't heard of it before and will give it a chance for sure 👌

 

Fun fact an alternate way to set the test case name -- instead of using setName in the test -- is to put the name of the test as the key value in the data provider. For example:

public function sessionDataProvider(): array
{
    return [
        'Fresh Session' => [
            'session' => [],
            'showLogin' => true,
            'showUpgrade' => false,
            'showPrimaryButton' => true,
        ]
    ];
}

Failing tests should output 'Fresh Session' instead of 'data set #0'

 

You're absolutely right, I didn't realize that before and also didn't notice it when writing up the code samples 🤦‍♂️ I've updated the post to reflect this. Thanks!

code of conduct - report abuse