neubert
neubert

Reputation: 16802

constructor breaks phpunit tests with providers

Here's a test PHPUnit test I wrote:

<?php
class MyTest extends PHPUnit_Framework_TestCase
{
    public function __construct()
    {
        echo "starting tests\r\n";

        parent::__construct();
    }

    public function provider()
    {
        return array(array('test'));
    }

    /**
    * @dataProvider provider
    */
    public function testProvider($var)
    {
        $this->assertEquals($var, $var);
        //exit($var);
    }
}

When I run it I get the following:

There was 1 error:

1) MyTest::testProvider
Missing argument 1 for MyTest::testProvider()

/home/myname/test.php:19

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

My question is... why? And what can I do about it?

In the actual unit tests I'm writing (the above is just a test demonstrating the problem) I'm testing a class with several different backend engines. I have an abstract class with a bunch of test cases and a protected class variable named $engine. I then have a bunch of classes that extend this abstract class and set $engine in the constructor. In each of the test methods in the abstract method $obj->setEngine($this->engine) is then called to test the specific engine in question. But this approach seems to break unit tests with providers and in lieu of that I'm not sure what I should be doing.

Any ideas?

Upvotes: 0

Views: 265

Answers (1)

gontrollez
gontrollez

Reputation: 6548

Instead of implementing a constructor, you should use the static method setUpBeforeClass to create the $engine. The engine must be stored in a static property.

https://phpunit.de/manual/current/en/fixtures.html#fixtures.sharing-fixture

Upvotes: 1

Related Questions