PHPUnit - PHP Fatal error: Call to a member function GetOne() on null
PHPUnit - PHP Fatal error: Call to a member function GetOne() on null
我今天开始在 PhpStorm 上使用 PHPUnit 测试。
我几乎可以测试所有功能,除了需要连接数据库的功能。
函数:
public function getProductID()
{
$this->product_id = $this->db->GetOne("select product_id from table1 where id = {$this->id}");
return $this->product_id['product_id'];
}
在我的测试用例中,出现错误:
PHP Fatal error: Call to a member function GetOne() on null
我定义了:
global $_db;
$this->db = $_db;
你应该mock/stub你的连接在你的测试中,比如
$stub = $this
->getMockBuilder('YourDBClass') // change that value with your REAL db class
->getMock();
// Configure the stub.
$stub
->method('GetOne')
->willReturn(); // insert here what you expect to obtain from that call
这样你的测试就与其他依赖项隔离开来。
如果您想进行不同类型的测试(例如,使用 REAL DB 数据),则不应进行单元测试,但 functional testing or integration testing
说明
这里您要测试的是 getProductID()
(一种方法),它应该 return 基本上是一个整数。时期。这是(或应该是)测试的目的。所以你只想检查一个整数是否是 returned,而不是那个整数是 returned。如果您停下来想一想,您可能会注意到您希望不受任何其他依赖结果的影响。
我今天开始在 PhpStorm 上使用 PHPUnit 测试。 我几乎可以测试所有功能,除了需要连接数据库的功能。
函数:
public function getProductID()
{
$this->product_id = $this->db->GetOne("select product_id from table1 where id = {$this->id}");
return $this->product_id['product_id'];
}
在我的测试用例中,出现错误:
PHP Fatal error: Call to a member function GetOne() on null
我定义了:
global $_db;
$this->db = $_db;
你应该mock/stub你的连接在你的测试中,比如
$stub = $this
->getMockBuilder('YourDBClass') // change that value with your REAL db class
->getMock();
// Configure the stub.
$stub
->method('GetOne')
->willReturn(); // insert here what you expect to obtain from that call
这样你的测试就与其他依赖项隔离开来。
如果您想进行不同类型的测试(例如,使用 REAL DB 数据),则不应进行单元测试,但 functional testing or integration testing
说明
这里您要测试的是 getProductID()
(一种方法),它应该 return 基本上是一个整数。时期。这是(或应该是)测试的目的。所以你只想检查一个整数是否是 returned,而不是那个整数是 returned。如果您停下来想一想,您可能会注意到您希望不受任何其他依赖结果的影响。