Php 测试递归方法
我想测试一种方法Php 测试递归方法,php,unit-testing,testing,phpunit,Php,Unit Testing,Testing,Phpunit,我想测试一种方法 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 {
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'
调用1次时,方法名称等于的预期失败
调用MyDriver::get('foo')的参数0与预期值不匹配。
断言两个字符串相等失败。
---期望
+++实际的
@@ @@
-“上次更新”
+“福”
很长一段时间我没有编写单元测试,很多人都忘记了。请帮助我理解。需要使用
$this->at(0)
和$this->at(1)
如果您仍在寻找关于这一点的指导,并且您不确定在哪里使用at()
这需要设置为预期的一部分,使用答案中的示例,它应该是这样的
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'));
}
在此上下文中,
处的将定义每次调用的使用时间 找到了解决办法。需要使用$this->at(0)和$this->at(1)