Skip to content

Instantly share code, notes, and snippets.

@a3dho3yn
Last active August 5, 2019 21:11
Show Gist options
  • Save a3dho3yn/70240ccbe98c45dec5574f5d1b053b05 to your computer and use it in GitHub Desktop.
Save a3dho3yn/70240ccbe98c45dec5574f5d1b053b05 to your computer and use it in GitHub Desktop.
How to use PHPUnit's @dataProvider in extended TestCase

PHPUnit @dataProvider simply doesn't work!

If you are using subclasses of PHPUnit's TestCase, you should call parent::__construct in order to benefit @dataProviders. But the tricky part is that TestCase::_construct receives some arguments. So, you should define them in your inherited class and pass them to the parent::__construct.

read more

<?php
namespace Tests\Feature;
use Tests\TestCase;
class DataProviderTest extends TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd($a, $b, $expected)
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider()
{
return [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 3]
];
}
}
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
class TestCase extends BaseTestCase
{
use CreatesApplication;
protected $headers = ['accept' => 'application/json'];
public function __construct()
{
parent::__construct(); // Illuminate\Foundation\Testing\TestCase has no __construct, so it bubbles up to PHPUnit\Framework\TestCase. But without any args
}
}
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
class TestCase extends BaseTestCase
{
use CreatesApplication;
protected $headers = ['accept' => 'application/json'];
public function __construct(?string $name = null, array $data = [], string $dataName = '')
{
parent::__construct($name, $data, $dataName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment