phpunit – Dataprovider可以从setUp获得连接

前端之家收集整理的这篇文章主要介绍了phpunit – Dataprovider可以从setUp获得连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
通过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,$c)
    {
        $this->db->query('SELECT `a`,`c` FROM `units`');

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

如果我通过dataProvider通过setUp函数连接数据库,它会响应致命错误调用成员函数query(),但如果连接到数据库本身有效,dataProvider可以获取setUp函数的设置吗?

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

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.

在你的情况下,我会为数据库使用单例/实例模式.

原文链接:https://www.f2er.com/php/137715.html

猜你在找的PHP相关文章