我今天开始在 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;
最佳答案
您应该在测试中模拟/ 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()
(一种方法),它基本上应该返回一个整数。时期。这是(或应该是)测试的目的。因此,您只想检查是否返回了整数,而不是返回了该整数。如果您停下来思考这一点,您可能会注意到您不希望受到任何其他依赖性结果的影响。
关于PHPUnit - PHP fatal error : Call to a member function GetOne() on null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35601483/