我想测试一个方法
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'
我很长时间没有写单元测试了,很多人都忘记了。帮助我理解。
如果您仍在寻找这方面的指导并且不确定在哪里使用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
将定义何时应使用每次调用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)