2012-11-05 41 views
8

我試圖用this method described by the author of PHPUnit嘲弄一個單身和存根其方法之一:PHPUnit存根方法返回NULL?

public function setUp() { 
    $this->_foo = $this->getMockBuilder('Foo') 
     ->disableOriginalConstructor() 
     ->getMock(); 

    $this->_foo->expects($this->any()) 
     ->method('bar') 
     ->will($this->returnValue('bar')); 

    var_dump($this->_foo->bar()); 
} 

的問題是,這個轉儲每次NULL。據我瞭解,當你嘲笑一個對象時,所有的方法都被替換爲存根,除非明確地像我所做的那樣剔除,否則返回NULL。所以,因爲我已經扼殺了bar()方法,爲什麼它不傾銷預期的'bar'字符串?我做錯了什麼?

回答

1

這最終導致我的PHPUnit版本出現問題。我已更新到最新的穩定版本,但無法複製該問題。

1

我希望這可以幫助,這是我的整個問題的複製品。它打印出所需的'酒吧'。我建議檢查您運行的是最新版本的phpunit和php,我運行:

PHPUnit 3.6.10和PHP 5.4.6-1ubuntu1。

$suite = new PHPUnit_Framework_TestSuite("TestTest"); 


class Foo { 

    function Bar() 
    { 
     return null; 
    } 
} 

class TestTest extends PHPUnit_Framework_TestCase 
{ 
    private $test_max_prod; 
    private $initial; 

    public function setUp() { 
     $this->_foo = $this->getMockBuilder('Foo') 
      ->disableOriginalConstructor() 
      ->getMock(); 

     $this->_foo->expects($this->any()) 
      ->method('bar') 
      ->will($this->returnValue('bar')); 

     var_dump($this->_foo->bar()); 
    } 

    function tearDown() { 

    } 

    function testTest(){} 



} 

輸出

PHPUnit 3.6.10 by Sebastian Bergmann. 

.string(3) "bar" 


Time: 0 seconds, Memory: 2.50Mb 

OK (1 test, 1 assertion) 

我希望這是有幫助的。

3

我遇到了同樣的問題,對我來說問題原來是我調用的方法不存在於原始對象上,並且正在由__call處理。解決方案結果如下:

$this->_foo->expects($this->any()) 
    ->method('__call') 
    ->with($this->equalTo('bar')) 
    ->will($this->returnValue('bar'));