CakePHP TimeHelper时间戳由phpunit视为对象

时间:2015-10-14 23:35:09

标签: php cakephp phpunit cakephp-3.0

我正在为使用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错误?或者我错过了什么?

1 个答案:

答案 0 :(得分:1)

  

这是一个TimeHelper错误吗?一个phpunit错误?或者我错过了什么?

首先阅读__toString()。阅读其他魔术方法不会受到伤害!你可以用它们做一些奇特的东西。然后是check the time class

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

assertEquals()将其视为真实的东西 - 一个对象。

假设您的save()这里的Table :: save()在后台执行稍微复杂一些,但是在进程结束时,如果该字段的类型为datetime,则它最终将作为数据库中的datetime字符串。这是因为Cake知道模式中的字段类型并将对象强制转换为正确的格式。

我猜你的意思是Debugger::dump()(更具体一点!) - 由于某种原因将它投射到字符串我猜,说实话,我现在懒得查看确切的行和理由。但我认为你已经明白了发生了什么。