在Laravel中模拟具有关系的模型 [英] Mocking models with a relationship in Laravel
问题描述
我试图创建一个CustomObject
的模型,然后使用与
$this->mock->shouldReceive('with')->once()->with('OtherObject');
$this->app->instance('CustomObject', $this->mock);
相同的东西将OtherObject
的检索链接到它上
$this->CustomObject->with('OtherObject')->get();
我似乎无法弄清楚如何在此末尾模拟此->get()
.我在构造函数方法['Eloquent', 'OtherObject', 'CustomObject']
中模拟了这两个模型.如果我删除->get()
,一切都将顺利运行,并且我的测试通过了(除了php错误,然后视图给了我,但是对于测试是否正常而言,这些都无关紧要.)
我目前所拥有的是:
$this->mock->shouldReceive('with')->once()->with('OtherObject');
$this->app->instance('CustomObject', $this->mock);
我应该怎么做才能模拟这个?
我专门尝试过->andReturn($this->mock)
,它仅告诉我在模拟对象上没有get方法.
您必须返回您的模拟实例,才能使下一个链接调用(->get()
)工作
$this->mock
->shouldReceive('with')
->once()
->with('OtherObject')
->andReturn($this->mock);
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.
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);
这篇关于在Laravel中模拟具有关系的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!