【问题标题】:Carbon object in mockery php test嘲笑php测试中的碳对象
【发布时间】:2021-02-06 12:10:03
【问题描述】:

感谢您的宝贵时间。我已经从代码/测试中去掉了绒毛。

我得到的最远的是 setAttribute 需要两个字符串作为参数,但我传入了一个 Carbon 对象,作为测试套件的 Mockery 不喜欢哪个?是这种情况吗,有没有更好的方法来使用 Mockery/PHPUnit 测试日期?其他测试和代码有效,似乎只有这个测试是一个问题。

错误

1) Tests\Unit\Services\StageServiceTest::update_stage
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_13_App_Entities_Subcategory::setAttribute('stage_updated_at', object(Carbon\Carbon)). Either the method was unexpected or its arguments matched no expected argument list for this method

Objects: ( array (
  'Carbon\\Carbon' => 
  array (
    'class' => 'Carbon\\Carbon',
    'properties' => 
    array (
    ),
  ),
))

小测试

        $subcategory = \Mockery::mock(Subcategory::class);
        $stage = \Mockery::mock(Stage::class);
        $subcategory
            ->shouldReceive('setAttribute')
            ->with('stage_updated_at', Carbon::now())
            ->once();
       $this->service->updateSubcategoryStage(self::SUBCATEGORY_ID, $stageId);

部分代码

        $subcategory->stage_updated_at = Carbon::now();
        $subcategory->save();

【问题讨论】:

    标签: php testing mockery


    【解决方案1】:

    从您的示例中不清楚是谁在打电话给setAttribute。但我猜你可能正在使用魔法二传手。

    您的期望失败的原因是您正在比较两个不同的对象。来自文档:

    When matching objects as arguments, Mockery only does the strict === comparison, which means only the same $object will match
    

    您可以使用equalTo hamcrest 匹配器来放松比较:

    $subcategory
        ->shouldReceive('setAttribute')
        ->with('stage_updated_at', equalTo(Carbon::now()))
        ->once();
    

    您仍然会遇到麻烦,因为时间总是会稍微偏离。幸运的是,Carbon 提供了一种方法来修复“现在”以用于测试目的。您只需在测试用例中设置它:

    Carbon::setTestNow('2020-01-31 12:13:14');
    

    【讨论】:

    • 抱歉响应缓慢,如果我安装了 hamcrest,我认为您的回答将解决问题,我尝试实施,但我无法让 hamcrest 工作。是否有不使用 hamcrest 的解决方案 - 或者我将如何调用 hamcrest 函数?非常感谢您的回答。
    • 要使用像equalTo这样的全局匹配函数,你必须使用\Hamcrest\Util::registerGlobalFunctions();注册它们。或者,您可以使用Hamcrest\Matchers::equalTo(Carbon::now())
    猜你喜欢
    • 2021-12-15
    • 2015-10-26
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2021-11-30
    • 2016-09-12
    • 1970-01-01
    相关资源
    最近更新 更多