2013-02-17 83 views
0

我有這樣的例子類如何使用PHPUnit模擬這些方法?

class Class 
{ 
    public function getStuff() 
    { 
     $data = $this->getData('Here'); 

     $data2 = $this->getData('There'); 

     return $data . ' ' . $data2; 
    } 

    public function getData($string) 
    { 
     return $string; 
    } 
} 

我希望能夠測試getStuff方法和模擬GetData方法。

嘲笑這種方法最好的方法是什麼?

由於

回答

3

我認爲getData方法應該是不同類的一部分,從邏輯分離的數據。然後,您可以通過這個類的一個模擬的TestClass實例作爲依賴性:

class TestClass 
{ 
    protected $repository; 

    public function __construct(TestRepository $repository) { 
    $this->repository = $repository; 
    } 

    public function getStuff() 
    { 
    $data = $this->repository->getData('Here'); 
    $data2 = $this->repository->getData('There'); 

    return $data . ' ' . $data2; 
    } 
} 

$repository = new TestRepositoryMock(); 
$testclass = new TestClass($repository); 

的模擬必須實現一個TestRepository接口。這被稱爲依賴注入。例如:

interface TestRepository { 
    public function getData($whatever); 
} 

class TestRepositoryMock implements TestRepository { 
    public function getData($whatever) { 
    return "foo"; 
    } 
} 

使用的接口,並在TestClass構造方法強制執行它的優點是接口保證了您定義,像getData()上述某些方法存在 - 無論實現,方法必須有。

+0

謝謝Gargon,這聽起來像是一個很好的解決方案。這將如何使用PHPUnit模擬對象完成? – Paulund 2013-02-17 15:29:25

+0

我認爲它是'$ mock = $ this-> getMock('TestRepository');'。有關更多示例,請參閱[PHPUnit文檔](http://www.phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects)。 – Gargron 2013-02-17 15:35:48