【问题标题】:Test a recursive method测试递归方法
【发布时间】:2014-06-28 14:19:18
【问题描述】:

我想测试一个方法

public function get($key)
{
    if (!($time = $this->driver->get($key))) {
        if ($key == self::LAST_UPDATE_KEY) {
            $time = new \DateTime();
            $this->driver->set($key, $time);
        } else {
            $time = $this->get(self::LAST_UPDATE_KEY); // need test this condition
        }
    }

    return $time;
}

驱动的第一个请求数据应该返回null,而第二个含义对我来说是必要的。

我写了一个测试

public function testGetEmpty()
{
    $time = new \DateTime();
    $driver_mock = $this
        ->getMockBuilder('MyDriver')
        ->getMock();
    $driver_mock
        ->expects($this->once())
        ->method('get')
        ->with('foo')
        ->will($this->returnValue(null));
    $driver_mock
        ->expects($this->once())
        ->method('get')
        ->with(Keeper::LAST_UPDATE_KEY)
        ->will($this->returnValue($time));

    $obj = new Keeper($driver_mock);
    $this->assertEquals($time, $obj->get('foo'));
}

执行时返回错误

Expectation failed for method name is equal to <string:get> when invoked 1 time(s)
Parameter 0 for invocation MyDriver::get('foo') does not match expected value.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'last-update'
+'foo'

我很久没有写单元测试了,很多人都忘记了。帮助我理解。

【问题讨论】:

  • 找到了解决方案。需要使用 $this->at(0) 和 $this->at(1)

标签: php unit-testing testing phpunit


【解决方案1】:

如果您仍在寻找有关此指南的指导,并且不确定在哪里使用at(),则需要将其设置为expects 的一部分,使用答案中的示例,它应该如下所示.

public function testGetEmpty()
{
    $time = new \DateTime();
    $driver_mock = $this
        ->getMockBuilder('MyDriver')
        ->getMock();
    $driver_mock
        ->expects($this->at(0))
        ->method('get')
        ->with('foo')
        ->will($this->returnValue(null));
    $driver_mock
        ->expects($this->at(1))
        ->method('get')
        ->with(Keeper::LAST_UPDATE_KEY)
        ->will($this->returnValue($time));

    $obj = new Keeper($driver_mock);
    $this->assertEquals($time, $obj->get('foo'));
}

在这种情况下,at 将定义每次调用的使用时间。

【讨论】:

    【解决方案2】:

    需要使用$this-&gt;at(0)$this-&gt;at(1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 2011-01-15
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多