2013-03-20 41 views
0

我遇到了一個類,它返回不可預知的值和單元測試調用該函數的方法的問題。所以我要改變方法的返回。PHPUnit連續調用

我無法嘲笑該方法,因爲我無法創建實例。這裏有一個例子:

// Class called MyClass 
public function doSomething(){ 
    $foo = new Foo(); 
    $bar = $foo->getSomethingUnpredictable(); 

    // Doing something with $bar and saves the result in $foobar. 
    // The result is predictable if I know what $foo is. 

    return $forbar; 
} 

// The test class 
public function testDoSomething{ 
    $myClass = new MyClass(); 
    when("Foo::getSomethingUnpredictable()")->thenReturns("Foo"); 

    // Foo::testDoSomething is now predictable and I am able to create a assertEquals 
    $this->assertEquals("fOO", $this->doSomething()); 
} 

我可以檢查哪些美孚::在單元測試testDoSomething回報,所以計算的結果,但不是testDoSomething只有從DoSomething的一些區別。我也無法檢查其他值會發生什麼。
doSomething不能有任何參數,因爲使用可變參數(所以我不能添加最佳參數)。

回答

0

這就是爲什麼硬連線依賴性不好,在其當前狀態doSomething不可測試。你應該重構MyClass這樣的:

public function setFoo(Foo $foo) 
{ 
    $this->foo = $foo; 
} 
public function getFoo() 
{ 
    if ($this->foo === null) { 
     $this->foo = new Foo(); 
    } 
    return $this->foo; 
} 
public function doSomething(){ 
    $foo = $this->getFoo(); 
    $bar = $foo->getSomethingUnpredictable(); 

    // Doing something with $bar and saves the result in $foobar. 
    // The result is predictable if I know what $foo is. 

    return $forbar; 
} 

然後,你將能夠注入你的嘲笑Foo例如:

$myClass->setFoo($mock); 
$actualResult = $myClass->doSomething(); 

至於如何存根的方法,這取決於你的測試框架。因爲這(when("Foo::getSomethingUnpredictable()")->thenReturns("Foo");)不是PHPUnit。