CakePHP TimeHelper时间戳被phpunit作为对象处理


CakePHP TimeHelper timestamp treated as object by phpunit

我正在为使用CakePHP TimeHelper的方法编写单元测试

public function testData()
{
    $timestamp = (string)Time::now()->i18nFormat('YYYY-MM-dd HH:mm:ss');
    // dump($timestamp); 
    // "2015-10-14 23:25:33"
    ...
    # data request should update the last_checkin field
    $screen = TableRegistry::get('Screens')->get(1);
    $this->assertEquals($timestamp, $screen->last_checkin);
}

我真的很困惑为什么它在控制器中工作,并且dump()的返回是正确的。但是单元测试失败,并显示以下消息:

1) App'Test'TestCase'Controller'ScreensControllerTest::testData
Failed asserting that Cake'I18n'Time Object &000000001a943b50000000016cb13674 (
    'date' => '2015-10-14 23:25:33.000000'
    'timezone_type' => 3
    'timezone' => 'UTC'
) matches expected '2015-10-14 23:25:33'.
/mysite/tests/TestCase/Controller/ScreensControllerTest.php:103

为什么assertEquals()认为它是一个对象时,dump()(和save()在我的控制器)认为它是一个字符串?

这是一个TimeHelper错误吗?phpunit bug?还是我错过了什么?

这是一个TimeHelper错误吗?phpunit bug?还是我错过了什么?

从阅读__toString()开始。顺便说一下,阅读其他魔法方法也不会有什么坏处!你可以用它们做一些奇妙的事情。然后检查时间类:

public function __toString()
{
    return $this->i18nFormat();
}

assertEquals()将其视为真实的对象。

假设Table::save()在这里为您的save()在后台做了一点更复杂,但是在过程结束时,如果字段是datetime类型,它将在DB中作为datetime字符串结束。这是因为Cake知道模式中的字段类型,并将对象转换为正确的格式。

我猜你的意思是Debugger::dump()(更具体!)-由于某种原因将其转换为string,我猜,老实说,我现在懒得看确切的行和原因。但是我想你已经明白是怎么回事了