PHPUnit - 类使用的模拟方法创建实例

时间:2018-05-04 09:23:12

标签: php unit-testing mocking phpunit instantiation

我想在类中模拟方法foo,但保留方法bar原样:

<?php

class MyClass
{
    protected $dep1;
    protected $dep2;
    protected $dep3;
    protected $dep4;

    /**
     * Test constructor.
     * @param $dep1
     * @param $dep2
     * @param $dep3
     * @param $dep4
     */
    public function __construct($dep1, $dep2, $dep3, $dep4)
    {
        $this->dep1 = $dep1;
        $this->dep2 = $dep2;
        $this->dep3 = $dep3;
        $this->dep4 = $dep4;

        parent::__construct();
    }

    public function foo()
    {
        return "foo";
    }

    public function bar()
    {
        return "bar";
    }
}

但是,MyClass通过工厂实例化,该工厂检索依赖项($dep1$dep2,...)并将它们直接注入MyClass的构造函数中。 所以我想使用该Factory并实例化一个MyClass对象(否则复杂的实例化也必须在测试用例中进行编码)。

简而言之,我想知道是否还有其他解决方案:

class TestMyClass extends \PHPUnit\Framework\TestCase {
    public function setUp()
    {
        // complicated way to retrieve $dep1 to $dep4

        $mock = $this->getMockBuilder(MyClass::class)->setMethods(['foo'])->setConstructorArgs([$dep1, $dep2, $dep3, $dep4])->getMock();
        $mock->expects($this->any())->method('foo')->willReturn(false);
    }
}

是否有可能以某种方式为已创建的MyClass实例创建代理,这只会覆盖foo方法?是否有另一种方法(没有runkit pecl扩展)来模拟现有/实例化对象的方法?

我知道PHPUnit有一些Proxy相关的方法,但我找不到任何文档/使用它们的例子,所以我不确定它们是否可以用来解决我的问题。

0 个答案:

没有答案
相关问题