phpSpec 没有找到 null 的 beCalled([array:0]) 匹配器

phpSpec no beCalled([array:0]) matcher found for null

我正在尝试使用 phpSpec 来设计我的 类。我无意中在我的一个事件处理程序上测试了一个句柄方法。

我的规格:

use App\Order;
use App\Models\Payments\Payment;
use App\Services\Payments\PaymentService;
use App\Events\Payments\AccountPayment;

class RecordPaymentTransactionSpec extends ObjectBehavior
{
    function let(PaymentService $paymentService)
    {
        $this->beConstructedWith($paymentService);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('App\Handlers\Events\Payments\RecordPaymentTransaction');
    }

    function it_should_record_payment_transaction(AccountPayment $event)
    {
        $this->paymentService->recordPayment($event)->shouldBeCalled();
    }
}

这是我的实现:

class RecordPaymentTransaction {

    public $paymentService;

    /**
     * Create the event handler.
     *
     * RecordPaymentTransaction constructor.
     * @param PaymentService $paymentService
     */
    public function __construct(PaymentService $paymentService)
    {
        $this->paymentService = $paymentService;
    }

    /**
     * Handle the event.
     *
     * @param  AccountPayment  $event
     * @return void
     */
    public function handle(AccountPayment $event)
    {
        $this->paymentService->recordPayment($event);
    }

}

但是,我不断收到此错误:

 - it should record payment transaction
      no beCalled([array:0]) matcher found for null.

看不出我做错了什么,请帮忙。

function it_should_record_payment_transaction(AccountPayment $event)
{
    $this->paymentService->recordPayment($event)->shouldBeCalled();
}

应该是

function it_should_record_payment_transaction(
    PaymentService $paymentService, 
    AccountPayment $event
) {
    $paymentService->recordPayment($event)->shouldBeCalled();
    $this->handle($event);
}

function it_should_record_payment_transaction(AccountPayment $event) 
{
    $prophet = new Prophet();
    $paymentService = $prophet->prophesize(PaymentService::class);

    $paymentService->recordPayment($event)->shouldBeCalled();
    $this->handle($event);

    $prophet->checkPredictions();
}

这是因为,当您指定一个 class 时,您应该只调用它的一个 public 方法并对协作者做出期望。

您不需要(也不应该)通过

呼叫协作者
$this->collaboratorName->method->shouldBeCalled()

使用 "implicit" 模拟(通过将它们传递到规范方法签名中:如果它们在 let 函数中使用并且具有相同的名称和类型,则它们 与 phpspec 相同的模拟)或 "explicit" 模拟,您可以通过在 Prophet 对象上调用 prophesize 获得。它们之间的唯一区别是 "implicit" 模拟是自动检查的,而 "explicit" 模拟需要手动检查 ($prophet->checkPredictions();)