Passing a mocked object as the instance in PHPUnit

2019-07-31 05:49发布

问题:

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!