gpt4 book ai didi

phpunit - Dataprovider 可以从 setUp 获取连接

转载 作者:行者123 更新时间:2023-12-04 01:56:35 24 4
gpt4 key购买 nike

通过 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 function 连接数据库,它响应 Fatal error: Call to a member function query() ,但如果连接到数据库本身有效,可以 dataProvider获取 setUp function的设定?

最佳答案

这是设计使然:为了确定测试的数量,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.



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

关于phpunit - Dataprovider 可以从 setUp 获取连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27287258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com