简体   繁体   中英

Mocking Laravel Model::increment() with Mockery

I have a line of code in a Laravel 5 event handler which looks like this:

$this->event->batch->increment('attempted_jobs');

$this->event is the event which calls the handler and $this->event->batch contains my Batch model. All this does in increment the attempted_jobs column within my database, so it's fairly basic stuff.

I would like to be able to test this event handler, I'm using Codeception and Mockery. My mock for $this->event->batch looks like this:

$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. 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? I've attempted creating a __call() mock, but this churns out tonnes of errors related to the increment() method not being implemented.

The issue was because, as stated, increment() is a protected method of Illuminate\\Database\\Eloquent\\Model() . The way to get around this is to mock the __call() method directly, like so:

$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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM