2015-02-09 107 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的一个小教程。