Search code examples
phpphpunitphpstorm

Call test dependency via UI


I have the following test structure:

public function testData() {
   $data = 10;
   // Test using $data
   return $data;
}
/**
 * @depends testData
 */
public function testSameData($data) {
    // More tests using data
}

This works fine when I run it as part of my test suite.

In PhpStorm however if I right-click on the function name I get the option "Run 'testSameData'" and when I click that it gives me:

This test depends on "Tests\testData" to pass.

Is there a (built-in or plugin) way to configure PhpStorm to automatically run the dependencies of a test if it's asked to run it as an individual function?


Solution

  • The @depends annotations tells phpunit that the test can only tun if the test it depends on has ran before.

    In your case, it seems what you need is a dataprovider: https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers

    A method that acts as dataProvider needs to return an array of arrays, like this:

    public function myTestData() : array
    {
        return [
            [10]
        ]
    }
    
    /**
     * @dataProvider myTestData
     */
    public function testSameData($data) 
    {
        // More tests using data
    }
    

    Note that the data provider will run the test for each array entry in the outer array. That way, you can have one test ran several times with different a dataset.

    Optionally, these data sets can be named:

    public function myTestData() : array
    {
        return [
            'Ten' => [10],
            'Five' => [5],
        ]
    }
    

    Edit: Notice I've changed the name of the dataprovider: if it starts with test, phpunit will consider it a test case by itself and probably warn about the lack of assertions.