我可以使用数据提供程序来加载我的文件,并对所有测试使用相同的提供程序,如下所示:
class mytest extends PHPUnit_Framework_TestCase {
public function contentProvider() {
return glob(__DIR__ . '/files/*');
}
/**
* @dataProvider contentProvider
*/
public function test1($file) {
$content = file_get_contents($file);
// assert something here
}
...
/**
* @dataProvider contentProvider
*/
public function test10($file) {
$content = file_get_contents($file);
// assert something here
}
}显然,这意味着如果我有10个测试用例,每个文件将加载10次。
我可以调整数据提供程序来加载所有文件,并返回一个包含所有内容的大结构。但是,由于每次测试都会单独调用提供程序,这仍然意味着每个文件都会加载10次,此外,它还会同时将所有文件加载到内存中。
我知道数据提供者也可以返回迭代器。但是phpunit似乎为每个测试分别重新运行迭代器,仍然导致加载每个文件10次。
有没有一种聪明的方法可以让phpunit只运行一次迭代器,并将结果传递给每个测试,然后再继续?
发布于 2017-03-14 04:09:23
测试依赖项
如果某些测试是依赖项,则应该使用@depends注释来声明Test dependencies。由依赖项返回的数据由声明此依赖项的测试使用。
但是,如果声明为依赖项的测试失败,则不会执行依赖项测试。
静态存储的数据
为了在测试之间共享数据,setup fixtures statically很常见。您可以对数据提供程序使用相同的方法:
<?php
use PHPUnit\Framework\TestCase;
class MyTest extends TestCase
{
private static $filesContent = NULL;
public function filesContentProvider()
{
if (self::$filesContent === NULL) {
$paths = glob(__DIR__ . '/files/*');
self::$filesContent = array_map(function($path) {
return [file_get_contents($path)];
}, $paths);
}
}
/**
* @dataProvider filesContentProvider
*/
public function test1($content)
{
$this->assertNotEmpty($content, 'File must not be empty.');
}
/**
* @dataProvider filesContentProvider
*/
public function test2($content)
{
$this->assertStringStartsWith('<?php', $content,
'File must start with the PHP start tag.');
}
}正如您所看到的,它不支持开箱即用。由于测试类实例在每次测试方法执行后被销毁,因此您必须将初始化数据存储在一个类变量中。
https://stackoverflow.com/questions/42754138
复制相似问题