Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel中具有关系的模拟模型_Php_Unit Testing_Laravel_Mockery - Fatal编程技术网

Php Laravel中具有关系的模拟模型

Php Laravel中具有关系的模拟模型,php,unit-testing,laravel,mockery,Php,Unit Testing,Laravel,Mockery,我试图创建一个对CustomObject的模拟,然后使用与 $this->CustomObject->with('OtherObject')->get(); 我似乎不知道如何在最后模拟这个->get()。我正在我的构造函数方法中模拟这两个模型['elount','OtherObject','CustomObject']。如果我删除->get(),一切都会顺利运行,我的测试也会通过(除了php错误之外,视图会告诉我这些错误,但是这些错误与测试是否正常工作无关) 我目前拥有的是:

我试图创建一个对
CustomObject
的模拟,然后使用与

$this->CustomObject->with('OtherObject')->get();
我似乎不知道如何在最后模拟这个
->get()
。我正在我的构造函数方法中模拟这两个模型
['elount','OtherObject','CustomObject']
。如果我删除
->get()
,一切都会顺利运行,我的测试也会通过(除了php错误之外,视图会告诉我这些错误,但是这些错误与测试是否正常工作无关)

我目前拥有的是:

$this->mock->shouldReceive('with')->once()->with('OtherObject');
$this->app->instance('CustomObject', $this->mock);
我该怎么做来嘲弄这一切


编辑:我特别尝试了Andreern($this->mock),它只告诉我在模拟对象上没有get方法。

您必须返回模拟的实例才能进行下一个链接调用(
->get()


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

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

您可以使用
mockry::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);

我已经试过了,但它仍然说我不能使用公共成员获取非对象。我不记得我的问题是什么,但你的方法肯定是正确的。
$mockQuery = m::mock();
$this->mock->shouldReceive('with')
    ->once()->with('OtherObject')
    ->andReturn($mockQuery);
$mockQuery->shouldReceive('get')->once()
    ->andReturn($arrayOfMocks);