PHPUnit - PHP fatal error : Call to a member function GetOne() on null

标签 php unit-testing phpunit

我今天开始在 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/

相关文章:

php - Selenium Webdriver和PHPUnit的屏幕截图

php - 尝试访问模型时找不到类 'App\models\Test'

php - 在 php 中验证电子邮件

javascript - 回显模式窗体上特定按钮的值

android - @Rule > 必须是 Kotlin Junit 测试中的公共(public) ValidationError

PHPUnit 在 xdebug 处于事件状态并正在监听的情况下运行时卡住

PHP:将依赖项打包在一个文件中

javascript - 将初始值设置为 Angular 表单组以进行测试

unit-testing - 在 Intellij IDEA 中启动慢速 Grails 测试

PHPUnit-Skelgen 1.2.0 不创建命名空间