如何编写CakePHP的单元测试:Model-> find()

时间:2018-10-01 12:47:04

标签: phpunit cakephp-2.0 phpunit-testing

我有一个使用model-> find()的方法。据我了解,我编写测试,必须使用模拟。我是编写测试的新手。你能告诉我搜索的方式吗?

 Pu? chiedermi il saldo

这是我在php单元测试中的代码。我试图写自己,但徒步旅行是不正确的。

function findSomethingInDB($client_id, $expiredLag): array
{
    $date = date("Y-m-d H:i:s", time() - $expiredLag);
    $conditions = [
        "DB.expires >" => $date,
        'client_id' => $client_id,
        'state' => 0,
    ];

    $result = $this->find('all', [
        'recursive' => -1,
        'conditions' => $conditions,
    ]);
    return $result;
}

该项目使用phpunit test 6.5.9

1 个答案:

答案 0 :(得分:0)

在您的findSomethingInDB()实现中,我可以看到您正在同一类中调用函数find()-$this->find(...)-我不确定为什么要将模拟注入原始类。

要实现的目标是部分模拟ErrorK50。基本上,在创建模拟时,您可以使用setMethods(['array','of','functions'])函数来指定要模拟的函数,以及必须正常运行的函数。

$errorK50PartialMock = $this->getMockBuilder(ErrorK50::class)
     ->setMethods(['find'])
     ->getMock();

$errorK50PartialMock->expects($this->once())
     ->method('find')
     ->willReturn($expected);

$result = $errorK50PartialMock->findErrorInDB($client_id, $expireLag);

$this->assertEquals($expected, $result);