Dataprovider 可以从 setUp 获取连接 [英] Dataprovider can get connection from setUp

查看:49
本文介绍了Dataprovider 可以从 setUp 获取连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

连接到数据库本身有效

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

如果我通过dataProvider通过setUp函数连接数据库,它会响应Fatal error: Call to a member function query(),但如果连接到数据库本身有效,dataProvider 能否获取setUp 函数 的设置?

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?

推荐答案

这是设计使然:为了确定测试的数量,PHPUnit 在实际运行测试(和 setUp 方法)之前运行 dataProviders.

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

来自 DataProvider 手册:

注意:所有数据提供程序都在调用 setUpBeforeClass 静态方法和第一次调用 setUp 方法之前执行.因此,您无法访问在数据提供程序中创建的任何变量.这是 PHPUnit 能够计算测试总数所必需的.

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.

这篇关于Dataprovider 可以从 setUp 获取连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆