Q:

Execute dataProviders only when needed in PHPUnit?

My test suite takes several minutes even just to begin. That because data providers are executed all at once at phpunit's start up and all their data (several thousands of objects) is kept in memory.
Is there a way to call dataProviders just before the test runs, instead? I don't care of seeing such a precise progress on screen.
Thanks

A:

It would take some refactoring but I'd suggest decking off the data providers from your test methods and instead make method calls within your actual tests to the data provider methods.
As you will already be aware, from PHPUnit's manual:
All data providers are executed before both the call to the setUpBeforeClass static method and the first call to the setUp method. Because of that you can't access any variables you create there from within a data provider. This is required in order for PHPUnit to be able to compute the total number of tests.
You should instead just shove those data providers into dumb classes that your test methods can call ad-hoc.
So instead of
/**
 * @dataProvider additionProvider
 */
public function testAdd($a, $b, $expected)
{
    $this->assertEquals($expected, $a + $b);
}

/**
 * As you know this will be executed before any tests, as will all of them
 */
public function additionProvider()
{
    return [
        [0, 0, 0],
        [0, 1, 1],
        [1, 0, 1],
        [1, 1, 3]
    ];
}

define your data providers in test base classes that extend PHPUnit\Framework\TestCase, organise them into logical groups, and extend your test classes off those.
class SomeDataProviderClass extends TestCase
{
    public function provideSomeData()
    {
        return [
            [0, 0, 0],
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 3]
       ];
    }
}

class AnActualTest extends SomeDataProviderClass
{
    public function testThatDependsOnSomeDataBeingProvided()
    {
        $data = $this->provideSomeData()
        // Use the data and do your test
    }
}

Obviously it's not ideal given how many tests you have but it's better organised this way other than having a lot of @dataProvider annotations all over the place (presumably; as you've not given any code I can't tell). All data provider methods will be organised logically and easier to maintain, and of course this should make the tests run a lot faster.
The only possible downside to this is if your data providers get stuff from databases, etc (again since you've not posted code I have no idea) as calling the same provider function multiple times will be a database round trip each time. You could easily cache the return value of such method calls, however.

