PHPUnit @dataProvider根本不起作用

时间:2012-04-16 13:50:22

标签: php phpunit

我已阅读有关该主题的文档,我的代码遵循数据提供程序实现的所有要求。首先,here's the full code of the test以防万一它是相关的。

这是实现数据提供者的功能:

/**
 * Test the createGroup function
 *
 * @return void
 * @author Tomas Sandven <tomas191191@gmail.com>
 *
 * @dataProvider provideFileImportTests_good
 **/
public function testCreateGroup($file, $groupname, $group, $mapping)
{
    // Create a test group
    $id = $this->odm->createGroup($groupname, $group);

    // Try to load it back out
    $result = R::load(OmniDataManager::TABLE_GROUP, $id);

    // Check that the result is not null
    $this->assertFalse(is_null($result));

    return $id;
}

PHPUnit失败了:

  

缺少参数1 for tests \ broadnet \ broadmap \ OmniDataManagerTest :: testCreateGroup()

我尝试在数据提供程序函数中杀死应用程序(die();),但它永远不会发生。数据提供程序函数在同一个类中公开可用,函数名中没有拼写错误,testCreateGroup函数在注释的注释中引用它,但数据提供程序函数从不被调用。

有人知道为什么吗?

8 个答案:

答案 0 :(得分:67)

最后,经过几个小时的推测这个测试文件,我发现仅仅定义构造函数会破坏数据提供者的功能。很高兴知道。

要修复它,只需调用父构造函数即可。以下是我的案例:

public function __construct()
{
    // Truncate the OmniDataManager tables
    R::wipe(OmniDataManager::TABLE_GROUP);
    R::wipe(OmniDataManager::TABLE_DATA);

    parent::__construct();   // <- Necessary
}

答案 1 :(得分:46)

如果你真的需要它,David Harkness有正确的提示。这是代码:

public function __construct($name = NULL, array $data = array(), $dataName = '') {
    $this->preSetUp();
    parent::__construct($name, $data, $dataName);
}

答案 2 :(得分:10)

要强调micro_user提出的要点,@dataProvider注释必须在docblock评论中。即这样做:

/**
 * @dataProvider myDataProvider
 *
 */
public function testMyMethod(...)
{
  ...
}

不要这样做,因为它不起作用:

/*
 * @dataProvider myDataProvider
 *
 */
public function testMyMethod(...)
{
  ...
}

答案 3 :(得分:8)

对我来说,只删除构造函数已经有效。在我的类测试中调用父构造函数也打破了注释,即使使用最新的PHPUnit(6.0.9)稳定版本也是如此。

我刚刚将__constructor上的代码移动到我的单元测试运行之前调用的setUp函数。

答案 4 :(得分:3)

确保dataProvider拼写正确... @dataProvidor vs @dataProvider

在需要数据提供者的测试功能中,需要一个包含

的docblock
/**
* @dataProvider providerItCanTest
*//

答案 5 :(得分:2)

该错误意味着数据提供程序方法返回的至少一个数据数组为空。例如:

public function dataProvider() {
    return array(
        array(1, 2, 3),
        array(),           // this will cause a "Missing argument 1" error
        array(4, 5, 6)
    );
}

因为您正在动态生成数据数组,所以您需要调试数据源并找出原因。

答案 6 :(得分:1)

对于仍然从谷歌来到这里的人们,您好!我使用的是PHP 7.0.5和PHPUnit 5.3.2。

正如@hubro所提到的 - 不要使用__construct(),因为它打破了一些PHPUnit注释。 Here是一个更详细的内容。

我的考试的班级MyStuffTest扩展了MyFancyTestcase,其范围为PHPUnit_Framework_TestCaseMyFancyTestcase使用了__construct()我遇到了同样的错误。它应该使用setupBeforeClass()来设置所有测试用例之间共享的静态数据 - 数据库连接等,不需要__construct()。 DataProvider现在可以使用了。

答案 7 :(得分:1)

花了几个小时试图找出dataProvider注释出了什么问题。根本根本没有调用它。

就我而言,问题是opcache。检查php.ini,确保已启用opcache.save_comments:

php -r "phpinfo();" | grep opcache.save_comments

要启用此功能,请将其添加到php.ini(或我的情况下为/usr/local/php5/php.d/20-extension-opcache.ini,因为我使用的是来自liip.ch的osx php):< / p>

[opcache]
opcache.save_comments=1
相关问题