簡體   English   中英

使用PHPunit刪除構造函數中的依賴項

[英]Removing a dependency in a constructor using 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));

    }

}

但是,這不起作用-在添加我的-> expects()之前調用Foo()的構造函數,因此模擬的getBarInstance()方法返回null。

有什么方法可以取消關聯的依賴關系,而不必重構類使用構造函數的方式?

使用getMock()$callOriginalConstructor參數。 將其設置為false 這是該方法的第五個參數。 在此處查找: http : //www.phpunit.de/manual/current/en/api.html#api.testcase.tables.api

其實等一下 您想將模擬傳遞給模擬嗎? 如果您確實getMock ,請使用getMock的第三個參數,該參數代表構造函數的參數。 在那里,您可以將Bar的模擬傳遞給Foo的模擬。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM