Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataprovider can get connection from setUp

Tags:

phpunit

Connect to database by setUp() failed

class ChanTest extends PHPUnit_Framework_TestCase
{
    protected $db;

    protected function setUp()
    {
        $this->db = new Core\Database('unitest');
    }

    /**
     * @dataProvider testProvider
     */
    public function testData($a, $b, $c)
    {
        $this->assertEquals($a + $b, $c);
    }

    public function testProvider()
    {
        $this->db->query('SELECT `a`, `b`, `c` FROM `units`');

        return $this->db->rows();
    }
}

Connect to database by itself works

class ChanTest extends PHPUnit_Framework_TestCase
{
    protected $db;

    protected function setUp()
    {
        $this->db = new Core\Database('unitest');
    }

    public function testData($a, $b, $c)
    {
        $this->db->query('SELECT `a`, `b`, `c` FROM `units`');

        foreach ($this->db->rows() as $item) {
            $this->assertEquals($item['a'] + $item['b'], $item['c']);
        }
    }
}

If I connect database by dataProvider through setUp function, it response Fatal error: Call to a member function query(), but if connect to database by itself works, can dataProvider get the setUp function's setting?

like image 680
Chan Avatar asked Dec 04 '14 05:12

Chan


1 Answers

This is by design: In order to determine the number of tests, PHPUnit runs dataProviders before actually running the tests (and the setUp method).

From the manual on DataProviders:

Note: All data providers are executed before both the call to the setUpBeforeClass static method and the first call to the setUp method. Because of that you can't access any variables you create there from within a data provider. This is required in order for PHPUnit to be able to compute the total number of tests.

In your case I'd use a singleton/instance pattern for the DB.

like image 83
Melle Avatar answered Sep 30 '22 20:09

Melle