Mocking models with a relationship in Laravel

核能气质少年 提交于 2019-12-24 17:01:37

问题


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.


回答1:


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



回答2:


You can use Mockery::self() to define chained expectations with arguments.

$this->mock->shouldReceive('with')
    ->once()->with('OtherObject')
    ->andReturn(m::self())->getMock()
    ->shouldReceive('get')->once()
    ->andReturn($arrayOfMocks);

In some cases you may need to split it up into two mocks:

$mockQuery = m::mock();
$this->mock->shouldReceive('with')
    ->once()->with('OtherObject')
    ->andReturn($mockQuery);
$mockQuery->shouldReceive('get')->once()
    ->andReturn($arrayOfMocks);



回答3:


It looks like I have it. It seems that the previous answer and my attempts were very close. The largest issue with using these is that a method is being called on the return object. If this isn't the best way to do this, I hope someone will correct me though.

$other_object = Mockery::mock('OtherObject');
$other_object->shouldReceive('get')->once()->andReturn(new OtherObject);

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

$this->app->instance('CustomObject', $this->mock);

and removing `OtherObject' from the constructor method.



来源:https://stackoverflow.com/questions/20361364/mocking-models-with-a-relationship-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!