[英]Mocking Laravel Model::increment() with Mockery
I have a line of code in a Laravel 5 event handler which looks like this: 我在Laravel 5事件处理程序中有一行代码,如下所示:
$this->event->batch->increment('attempted_jobs');
$this->event
is the event which calls the handler and $this->event->batch
contains my Batch
model. $this->event
是调用处理程序的事件, $this->event->batch
包含我的Batch
模型。 All this does in increment the attempted_jobs
column within my database, so it's fairly basic stuff. 所有这些都会增加我的数据库中的
attempted_jobs
列,所以这是相当基本的东西。
I would like to be able to test this event handler, I'm using Codeception and Mockery. 我希望能够测试这个事件处理程序,我正在使用Codeception和Mockery。 My mock for
$this->event->batch
looks like this: 我对
$this->event->batch
模拟看起来像这样:
$batch = m::mock('MyVendor\MyApp\Batch');
$batch->shouldReceive('increment')->once()->with('attempted_jobs');
This however causes issues - increment()
is a protected method of Model
and therefore cannot be mocked. 然而,这会导致问题 -
increment()
是Model
的受保护方法,因此无法进行Model
。 Here's the exact error: 这是确切的错误:
InvalidArgumentException: increment() cannot be mocked as it a protected method and mocking protected methods is not allowed for this mock
It appears to be implemented using the __call()
PHP magic method, so how to I mock this? 它似乎是使用
__call()
PHP魔术方法实现的,那么如何模拟这个呢? I've attempted creating a __call()
mock, but this churns out tonnes of errors related to the increment()
method not being implemented. 我试图创建一个
__call()
模拟,但这会产生大量与increment()
方法无关的错误。
The issue was because, as stated, increment()
is a protected method of Illuminate\\Database\\Eloquent\\Model()
. 问题是因为,如上所述,
increment()
是Illuminate\\Database\\Eloquent\\Model()
的受保护方法。 The way to get around this is to mock the __call()
method directly, like so: 解决这个问题的方法是直接模拟
__call()
方法,如下所示:
$batch = m::mock('MyVendor\MyApp\Batch');
$batch->shouldReceive('__call')->with('increment')->once();
(I'm not sure why this didn't work when I first tried it though) (我不知道为什么当我第一次尝试时这不起作用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.