kabirbaidhya
kabirbaidhya

Reputation: 3490

PHPUnit: dataProvider not working in the sub classes of PHPUnit_Framework_TestCase

I'm using classes extended from PHPUnit_Framework_TestCase in my tests. And it seems like the @dataProvider doesn't work for these extended classes.

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:

enter image description here

If I use \PHPUnit_Framework_TestCase instead of TestCase then it works fine. But it's not working for these extended classes: TestCase & ApiTestCase.

TestCase class

namespace HH\Api\V10;

use HH\Api\ApiTestCase;

class TestCase extends ApiTestCase
{
}

ApiTestCase class

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

Upvotes: 2

Views: 889

Answers (2)

kabirbaidhya
kabirbaidhya

Reputation: 3490

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.

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(),
    ]);
}

Upvotes: 4

mrosiu
mrosiu

Reputation: 71

You should use setUp fixture for setting the $client

Upvotes: 2

Related Questions