我正试图进入使用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.
看不出我在这里做错了什么,请帮忙。
答案 0 :(得分:2)
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()
使用“隐式”模拟(通过将它们传递给spec方法签名:如果它们在let
函数中使用并且具有相同的名称和类型,则它们是与phpspec相同的模拟)或者通过调用prophesize
对象上的Prophet
可以获得“显式”模拟。它们之间的唯一区别是自动检查“隐式”模拟,而需要手动检查“显式”模拟($prophet->checkPredictions();
)