编程语言
首页 > 编程语言> > php – mockery重载类缺少方法

php – mockery重载类缺少方法

作者:互联网

需要使用Mockery的一些帮助 – 我想重载一个类,它是在方法中使用新的HelperUtil()创建的.

使用Mockery重载我可以这样做,但它留给我一个空的shell类.然后,我似乎必须创建所有被调用的方法.有没有办法创建一个重载的完整模拟,然后只更改一个方法?

    $mock = \Mockery::mock('overload:'.HelperUtil::class);
    $mock->shouldReceive('content')->andReturnUsing(function() {
        return 'different content';
    });

谢谢

编辑:
我想我想做:

    $mock = \Mockery::mock('overload:'.HelperUtil::class)->shouldDeferMissing();
    $mock->shouldReceive('content')->andReturnUsing(function() {
        return 'different content';
    });

但那仍然很有效=(

解决方法:

在GitHub上有一个关于它的interesting discussion

shouldIgnoreMissing and shouldDeferMissing (and other such flags
present and future) do work, but not on the mock, but on the instance
mock.

Sounds confusing, but it’s because of internals.

When you do a m::mock('overload:Foo'); mockery goes and creates a new
class called Foo based on the Mock.php “template”. And that template
has the _mockery_ignoreMissing flag set to false by default.

Once the mock method gets to the end, it creates an overloaded Foo
object and returns it to us. The overloaded Foo class is also
available to instantiate new Foo objects.

Calling $m->shouldIgnoreMissing() sets the ignore missing flag on the
object that was returned by the mock method.

Calling new Foo() creates a new instance of the Foo object that has
the Mock.php templates default of false for _mockery_ignoreMissing.

If you want the flag set to true on the new instance, you need to call
shouldIgnoreMissing() on that instance, and not on $m.

我看,功能“should ignore missing on instance mocks”已经完成,所以你能做的最好

$mock = \Mockery::mock('overload:'.HelperUtil::class)->shouldIgnoreMissing();

我没有看到shouldDeferMissing已经完成了重载.

当然,作为一种解决方法,您可以考虑创建一个模拟并注入它.

标签:php,unit-testing,testing,phpunit,mockery
来源: https://codeday.me/bug/20190627/1308292.html