php - mock php测试中的碳对象

标签 php testing mockery

感谢您的时间。我已经从代码/测试中去除了绒毛。
我得到的最远的是 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();

最佳答案

从你的例子中不清楚谁在打电话 setAttribute .但我猜你可能正在使用魔法二传手。
您的期望失败的原因是因为您正在比较两个不同的对象。从文档:

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

您可以使用 equalTo 来放松比较。火腿匹配器:
$subcategory
    ->shouldReceive('setAttribute')
    ->with('stage_updated_at', equalTo(Carbon::now()))
    ->once();
你仍然会遇到麻烦,因为时间总是会稍微偏离。幸运的是,Carbon 提供了一种用于测试目的的“现在”修复方法。你只需要在你的测试用例中设置它:
Carbon::setTestNow('2020-01-31 12:13:14');

关于php - mock php测试中的碳对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64499803/

相关文章:

php - Mocking Laravel Eloquent 模型 - AppServiceProvider 中使用的 Mocking 模型

php - 如何在电报机器人中创建链接

php - 简单的 PHP 邮件功能不适用于亚马逊服务器 EC2

php - mock :检查参数至少传递了一次?

eclipse - 如何在eclipse IDE中执行go test文件

node.js - 如何在 Angular jest 测试中调用 Nodejs 的垃圾回收?使用 Node v20 进行测试很慢并且存在内存泄漏

PHPUnit 模拟一个对象的属性

php - 取消设置 $this

php - 如何通过模型 ID 和模型类型在 Laravel 中创建关系

Java 解析器测试