简体   繁体   English

PHPUnit:dataProvider在PHPUnit_Framework_TestCase的子类中不起作用

[英]PHPUnit: dataProvider not working in the sub classes of PHPUnit_Framework_TestCase

I'm using classes extended from PHPUnit_Framework_TestCase in my tests. 我在测试中使用了从PHPUnit_Framework_TestCase扩展的类。 And it seems like the @dataProvider doesn't work for these extended classes. 看来@dataProvider对于这些扩展类不起作用。

Here's just a simple test 这只是一个简单的测试

namespace HH\Api\V10;

class StupidityTest extends TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function testAdd($a, $b, $expected)
    {
        $this->assertEquals($expected, $a + $b);
    }

    public function additionProvider()
    {
        return [
          [0, 0, 0],
          [0, 1, 1],
        ];
    }
}

phpunit returns this error: phpunit返回此错误:

在此处输入图片说明

If I use \\PHPUnit_Framework_TestCase instead of TestCase then it works fine. 如果我使用\\PHPUnit_Framework_TestCase而不是TestCase那么它将正常工作。 But it's not working for these extended classes: TestCase & ApiTestCase . 但不适用于以下扩展类: TestCaseApiTestCase

TestCase class TestCase

namespace HH\Api\V10;

use HH\Api\ApiTestCase;

class TestCase extends ApiTestCase
{
}

ApiTestCase class ApiTestCase

namespace HH\Api;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\Response;

class ApiTestCase extends \PHPUnit_Framework_TestCase
{
    protected $client = null;

    public function __construct()
    {
        parent::__construct(); // <--have called parent constructor
        $this->client = new Client([
            'base_url' => $this->url(),
        ]);
    }
    ....
}

Any help would be really appreciated. 任何帮助将非常感激。 Thanks 谢谢

Finally figured out why it didn't work out. 最终弄清楚了为什么它没有解决。

The constructor of the sub class needs to be identical to that of the parent class PHPUnit_Framework_TestCase . 子类的构造函数必须与父类PHPUnit_Framework_TestCase的构造函数相同。

class ApiTestCase extends \PHPUnit_Framework_TestCase
{
    protected $client = null;

    public function __construct($name = null, array $data = array(), $dataName = '')
    {
        parent::__construct($name, $data, $dataName);
        ...
    }
 ...
}

But I found out that the better way to do this was not through the constructor but with fixtures. 但是我发现更好的方法不是通过构造函数,而是通过夹具。

public function setUp()
{
    $this->client = new Client([
        'base_url' => $this->url(),
    ]);
}

您应该使用setUp夹具来设置$client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM