通过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.
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.
在你的情况下,我会为数据库使用单例/实例模式.