2015-02-09 109 views
2

我剛開始玩弄PHPUnit,想知道是否可以用存根覆蓋/替換方法。我有興農一定的經驗,並與興農這是可能的(http://sinonjs.org/docs/#stubsPHPUnit用存根覆蓋實際方法

我想是這樣的:

<?php 

class Foo { 

    public $bar; 

    function __construct() { 
    $this->bar = new Bar(); 
    } 

    public function getBarString() { 
    return $this->bar->getString(); 
    } 

} 

class Bar { 

    public function getString() { 
    return 'Some string'; 
    } 

} 



class FooTest extends PHPUnit_Framework_TestCase { 

    public function testStringThing() { 
    $foo = new Foo(); 

    $mock = $this->getMockBuilder('Bar') 
     ->setMethods(array('getString')) 
     ->getMock(); 

    $mock->method('getString') 
     ->willReturn('Some other string'); 

    $this->assertEquals('Some other string', $foo->getBarString()); 
    } 

} 

?> 

回答

2

這樣可不行,你就不能嘲笑裏面的酒吧實例Foo實例。 Bar在Foo的構造函數中被實例化。

更好的方法是將Foo的依賴項注入Bar,i。 e .:

<?php 

class Foo { 

    public $bar; 

    function __construct(Bar $bar) { 
    $this->bar = $bar; 
    } 

    public function getBarString() { 
    return $this->bar->getString(); 
    } 
} 

class Bar { 

    public function getString() { 
    return 'Some string'; 
    } 

} 

class FooTest extends PHPUnit_Framework_TestCase { 

    public function testStringThing() { 

    $mock = $this->getMockBuilder('Bar') 
     ->setMethods(array('getString')) 
     ->getMock(); 

    $mock->method('getString') 
     ->willReturn('Some other string'); 

    $foo = new Foo($mock); // Inject the mocked Bar instance to Foo 

    $this->assertEquals('Some other string', $foo->getBarString()); 
    } 
} 

請參閱http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146瞭解DI的一個小教程。