首页 > 解决方案 > PHP Prophecy ->reveal() 方法 - 我应该将期望(如“willReturn”、“ShouldBeCalled”)放在它之前还是之后?

问题描述

现在使用 PHP Prophecy。我有两个代码示例:一个:

$aProphecy = $this->prophesize(A::class);
$aProphecy->someMethod()->willReturn([]);
//now can be used:
$aProphecy->reveal();

$aProphecy = $this->prophesize(A::class);
$aProphecy->reveal();
$aProphecy->someMethod()->willReturn([]);

我不明白哪个是正确的方法,为什么?

标签: phptestingprophecy

解决方案


此时您的示例顺序无关紧要,因为这两种情况都将被评估。但是,我更喜欢第一个变体,因为它更清楚 $aProphecy 的预期。

需要注意的重要一点是,您的代码没有检查任何内容,因为您需要将 $aProphecy 注入另一个对象并在那里显示它:

$aProphecy = $this->prophesize(A::class);
$aProphecy->someMethod()->willReturn([]);
$bObject = new B($aProphecy->reveal());
$bObject->methodWhichCallSomeMethodInside();
// check if someMethod was called exactly once
$aProchecy->someMethod()->shouldBeCalled(); 

推荐阅读