【问题标题】:Writing tests for class using TableGateway ZF2/ZF3使用 TableGateway ZF2/ZF3 编写类测试
【发布时间】:2017-10-26 13:05:06
【问题描述】:

我在进行测试时遇到问题。

我在课堂上创建了一个函数来计算数据库表中的所有行。要访问数据库,我使用 Zend Frameworks TableGateway class。我的问题是我不知道如何为函数编写测试。

一种看待它的方式是,该功能非常简单,不需要测试,但如果知道如何让它工作,那就太好了。

AbstractTableGateway 上没有允许我设置内部变量 $adapter 的函数。如何设置受保护的变量 $adapter?

功能

public function count()
{
    $sql = "SELECT COUNT(*) AS Count FROM ". $this->tableGateway->getTable();
    $statement = $this->tableGateway->adapter->query($sql);
    $result    = $statement->execute()->current();
    return $result['Count'];
}

功能测试

public function testCount()
{
    $sql = "SELECT COUNT(*) AS Count FROM DbTable";

    $result = $this->prophesize(Result::class);
    $result->current()->willReturn(["Count" => 10]);

    $statement = $this->prophesize(Statement::class);
    $statement->execute()->willReturn($result);

    $adapter = $this->prophesize(Adapter::class);
    $adapter->query($sql)->willReturn($statement);

    $this->tableGateway->adapter = $adapter;

    $this->assertSame(10, $this->DbTable->count());
}

【问题讨论】:

    标签: php zend-framework zend-framework2 phpunit


    【解决方案1】:

    TableGateway 从构造函数中获取它的适配器。无论工厂在您的 $this->tableGateway 属性中创建 TableGateway 实例,都应该将您的模拟适配器(或真正的适配器,如果这旨在作为集成测试)传递给它的构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多