danvim
136
2
Testing

Mocking find($collection) in repository pattern in Laravel with Mockery

Posted 1 month ago by danvim

I'm doing unit testing and my repository has this method:

/**
 * @param int|Collection $id
 * @return MyModel|Collection|null
 */
 public function find($id);

I tried this:

$this->package_repo = Mockery::mock(PackageRepositoryInterface::class);
$this->app->instance('Package', $this->package_repo);
// ...
$this->ticket_repo->shouldReceive("find")->with(collect([]))->andReturn(/*...*/);

//...

echo $this->ticket_repo->find(collect([]));  // Failed here.

The test immediately failed, and I think it's because the 2 collections in the shouldReceive expectation statement and the actual find statement are distinct objects.

If I want to mock the behavior of $this->ticket_repo->find($ids), what should I do?

Or rather, if there is a better way to design a testable algorithm, how would it be? Because I would like to have all the ids to I want to find be in an array, and be constructed into a single SQL select query, instead of a few hundred separate ones, for performance purposes.

Also asked here: https://stackoverflow.com/questions/56525501/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery

Please sign in or create an account to participate in this conversation.