【问题标题】:phpSpec no beCalled([array:0]) matcher found for nullphpSpec no beCalled([array:0]) matcher found for null
【发布时间】:2016-09-26 22:58:32
【问题描述】:

我正在尝试使用 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.

看不到我在这里做错了什么,请帮忙。

【问题讨论】:

    标签: laravel-5 phpspec


    【解决方案1】:
    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();
    }
    

    这是因为,当您指定一个类时,您应该只调用它的公共方法并对合作者提出期望。

    您不需要(而且您不应该这样做)用

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

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

    【讨论】:

    • 这有效,非常感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2012-08-13
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多