我正试图创建一个CustomObject
的模型,然后使用与相同的东西将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方法。
您必须返回mock的一个实例,才能进行下一个链接调用(->get()
)以使工作
$this->mock
->shouldReceive('with')
->once()
->with('OtherObject')
->andReturn($this->mock);
您可以使用Mockery::self()
定义带参数的链式期望。
$this->mock->shouldReceive('with')
->once()->with('OtherObject')
->andReturn(m::self())->getMock()
->shouldReceive('get')->once()
->andReturn($arrayOfMocks);
在某些情况下,您可能需要将其拆分为两个模拟:
$mockQuery = m::mock();
$this->mock->shouldReceive('with')
->once()->with('OtherObject')
->andReturn($mockQuery);
$mockQuery->shouldReceive('get')->once()
->andReturn($arrayOfMocks);
看起来我有它。似乎之前的答案和我的尝试非常接近。使用这些方法的最大问题是在返回对象上调用了一个方法。如果这不是最好的方法,我希望有人能纠正我。
$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);
以及从构造函数方法中删除"OtherObject"。