PHPUnit - PHP 致命错误:在 null 上调用成员函数 GetOne()


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 致命错误:在空值上调用成员函数 GetOne()

我已经定义了:

global $_db;
$this->db = $_db;
你应该

在测试中模拟/存根你的连接,比如

$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数据),你不应该做单元测试,而应该做功能测试或集成测试

解释

在这里,您正在测试的是getProductID()(一种方法),它基本上应该返回一个整数。时期。这是(或应该是)测试的目的。因此,您只想检查是否返回整数,而不是返回该整数。如果您停下来思考这个问题,您可能会注意到您希望不受任何其他依赖结果的影响。