使用 TableGateway ZF2/ZF3 为 class 编写测试

Writing tests for class using TableGateway ZF2/ZF3

我做测试有问题。

我在 class 中创建了一个函数,用于计算数据库 table 中的所有行。为了访问数据库,我使用 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());
}

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