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