将模拟对象作为实例传递给PHPUnit/Laravel [英] Passing a mocked object as the instance in PHPUnit/Laravel

查看:53
本文介绍了将模拟对象作为实例传递给PHPUnit/Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在嘲笑一个对象,并像这样编写测试...

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()包含对internalMethod()的调用,就像这样...

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

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

...但是到执行到达$this->internalMethod()的调用时,$this现在是原始$purchase对象的实例,而不是$purchase_m模拟对象的实例.

... 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.

因此,对$this->internalMethod()的函数调用不会像我们希望的那样返回"GOLD".

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

任何指针将不胜感激.

Any pointers would be greatly appreciated.

推荐答案

嘿,没关系!解决了.

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!

这篇关于将模拟对象作为实例传递给PHPUnit/Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆