Passing a mocked object as the instance in PHPUnit/Laravel

主宰稳场 提交于 2019-12-11 05:54:13

问题


I'm mocking an object and writing a test like so...

public function test_mocked_object(){
    $purchase = new Purchase();
    $purchase_m = \Mockery::mock($purchase);
    $purchase_m->shouldReceive('internalMethod')->andReturn('GOLD');

    $purchase_m->testMethod('test');
}

testMethod() contains a call to internalMethod(), like so...

public function testMethod($string){
    $this->internalMethod();
}

... but by the time execution reaches the call to $this->internalMethod(), $this is now an instance of the original $purchase object, and not an instance of the $purchase_m mocked object.

Therefore, the function call to $this->internalMethod() does not return "GOLD" as we were hoping.

Any pointers would be greatly appreciated.


回答1:


hehe nevermind! Solved it.

$shpm \Mockery::mock(Purchase::class)->makePartial();

By creating a partial mock, you keep the instance intact when calling methods on it.

Hope this helps someone!



来源:https://stackoverflow.com/questions/44264952/passing-a-mocked-object-as-the-instance-in-phpunit-laravel

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