Search code examples
phpunit-testinglaravelmockery

Mocking models with a relationship in Laravel


I'm attempting to create a Mockery of CustomObject then chain the retrieval of OtherObject onto it using something identical to

$this->CustomObject->with('OtherObject')->get();

I can't seem to figure out how to mock this ->get() at the end there. I'm mocking both of those models in my constructor method ['Eloquent', 'OtherObject', 'CustomObject']. If I remove the ->get() everything runs smoothly and my tests pass (aside from the php errors the view is then giving me, but those don't matter if the test is working correctly).

What I currently have is this:

$this->mock->shouldReceive('with')->once()->with('OtherObject');
$this->app->instance('CustomObject', $this->mock);

What should I be doing to mock this?

Edit: I have specifically attempted ->andReturn($this->mock) which only tells me that on the mocked object there is no get method.


Solution

  • You must return an instance of your mock to make the next chaining call (->get()) to work

    $this->mock
         ->shouldReceive('with')
         ->once()
         ->with('OtherObject')
         ->andReturn($this->mock);