【问题标题】:How to write unit test for CakePHP: Model->find()如何为 CakePHP 编写单元测试:Model->find()
【发布时间】:2018-10-01 12:47:04
【问题描述】:

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

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;
}

这是我在 php 单元测试中的代码。我试着给自己写,但远足是不对的。

public function testFindSomethingInDB()
{
    $client_id = '1';
    $expireLag = '0';

    $expected = [
        '0' => [
            'DB' => [
                'id' => '3068',
                'procedure_id' => '1',
                'client_id' => '1',
                'object' => 'test',
                'date' => '2034-02-09 22:05:37',
                'entity' => 'test',
                'freshness' => '-354923520',
                'expires' => '2022-11-12 00:13:37',
            ],
        ],
    ];

    $mysql = $this->getMockBuilder(ErrorK50::class)
                  ->getMock();
    $mysql->expects($this->any())
          ->method('findSomethingInDB')
          ->with($this->equalTo($client_id), $this->equalTo($expireLag))
          ->will($this->returnValue($expected));
    $errorK50 = new ErrorK50($mysql);
    $result = $errorK50->findSomethingInDB($client_id, $expireLag);

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

项目使用phpunit test 6.5.9

【问题讨论】:

  • 你想测试什么?目前还不清楚。 findErrorInDB() 的功能是什么?那个函数是在调用findSomethingInDB() 吗?
  • findSomethingInDB 调用方法 find

标签: cakephp-2.0 phpunit


【解决方案1】:

在您的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2012-01-06
    • 2019-03-17
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多