php - 使用 PHPunit 删除构造函数中的依赖项

标签 php unit-testing phpunit

在尝试测试遗留代码库时,我遇到了一个执行以下操作的对象:

class Foo
{
    public function __construct($someargs)
    {
        $this->bar = new Bar();
        // [lots more code]
    }
}

在这个实例中,Bar 有一个构造函数,它做了一些坏事,例如连接到数据库。我试图集中精力测试这个 Foo 类,因此将其更改为如下所示:

class Foo
{
    public function __construct($someargs)
    {
        $this->bar = $this->getBarInstance();
        // [lots more code]
    }

    protected function getBarInstance()
    {
        return new Bar();
    }
}

并尝试通过以下 PHPUnit 测试来测试它:

class FooTest extends PHPUnit_Framework_TestCase
{
    public function testInstance()
    {

        $bar = $this->getMock('Bar');
        $foo = $this->getMock('Foo', array('getBarInstance'));
        $foo->expects($this->any())
            ->method('getBarInstance')
            ->will($this->returnValue($bar));

    }

}

但是这不起作用 - Foo() 的构造函数在添加 ->expects() 之前被调用,因此模拟的 getBarInstance() 方法返回 null。

是否有任何方法可以取消这种依赖关系,而不必重构类使用构造函数的方式?

最佳答案

使用getMock()$callOriginalConstructor 参数。将其设置为false。这是该方法的第五个参数。在这里查找:http://www.phpunit.de/manual/current/en/api.html#api.testcase.tables.api

其实,等等。你想将模拟传递给模拟吗?如果您确实想要这样做,请使用 getMock 的第三个参数,它代表构造函数的参数。在那里,您可以将 Bar 的模拟传递给 Foo 的模拟。

关于php - 使用 PHPunit 删除构造函数中的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427738/

相关文章:

php - CakePHP 如何从另一个 Controller 检索数据?

PHP MySQL 执行多个相关查询的最佳方式

ios - 如何将核心数据用于主要应用程序和单元测试?

使用内部对象进行 Java 单元测试

php - 模拟类时出现 Mockery TypeError

unit-testing - 在 laravel 测试中调用命名路由

php mysqli stmt num_rows 总是返回 0

php - 在没有 exec 的情况下创建 zip 或 tar.gz 存档

javascript - ReactJS 单元测试 - TypeError : this. props.onChange 不是函数

php - Travis-CI:即使使用自动加载器也找不到类