1

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.

4

3 回答 3

2

您必须返回一个模拟实例才能使下一个链接调用 ( ->get()) 起作用

$this->mock
     ->shouldReceive('with')
     ->once()
     ->with('OtherObject')
     ->andReturn($this->mock);
于 2013-12-03T21:05:50.860 回答
1

您可以使用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);
于 2014-01-03T11:17:12.450 回答
0

看起来我有它。似乎之前的答案和我的尝试非常接近。使用这些的最大问题是在返回对象上调用了一个方法。如果这不是最好的方法,我希望有人能纠正我。

$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”。

于 2013-12-04T06:44:44.933 回答