PHPUnit - Don't fail when the dataProvider returns an empty array

谁说我不能喝 提交于 2019-12-23 12:01:11

问题


I have a PHPUnit test which uses a @dataProvider. The dataprovider checks the filesystem for certain files.

However I'm using this test in different environments what means it can happen that the files do not exist. This means that the dataProvider does not find anything and that the test is not executed.

And this causes the test run to end in a failure.

Question: is the a way to configure PHPUnit to ignore tests which have providers that produce nothing?


回答1:


While I do not know of any phpunit option (which doesn't mean one doesn't exist), you could just use something like the following:

public function providerNewFileProvider()
{
    //get files from the "real" provider
    $files = $this->providerOldFileProvider();
    //no files? then, make a fake entry to "skip" the test
    if (empty($files)) {
        $files[] = array(false,false);
    }

    return $files;
}

/**
* @dataProvider providerNewFileProvider
*/

public function testMyFilesTest($firstArg,$secondArg)
{
    if (false === $firstArg) {
        //no files existing is okay, so just end immediately
        $this->markTestSkipped('No files to test');
    }

    //...normal operation code goes here
}

It's a workaround, sure, but it should stop an error from showing up. Obviously, whatever you do will depend on whether the first (or any arbitrary) argument is allowed to be false, but you can make tweaks to fit your tests.




回答2:


You can mark a test as skipped in the data provider as well, so it won't fail, nor you have to add a wrapper data provider as suggested in the other answer.

public function fileDataProvider()
{
    $files = $this->getTestFiles();
    if (empty($files)) {
        $this->markTestSkipped('No files to test');
    }

    return $files;
}

/**
 * @dataProvider fileDataProvider
 */

public function testMyFilesTest($firstArg, $secondArg)
{
    //...normal operation code goes here
}


来源:https://stackoverflow.com/questions/23855492/phpunit-dont-fail-when-the-dataprovider-returns-an-empty-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!