2013-05-01 132 views
0

我正在學習使用PHPUnit進行單元測試,並且遇到了我無法解析的模擬對象的一個​​奇怪問題。我設置了這些假文件,我所經歷的例子:PHPUnit模擬對象方法

Class1的

class PrimaryObj1 
{ 
    function doNothing(SecondObj $s) 
    { 
    } 
} 

的Class2

class PrimaryObj2 
{ 
    function doNothing(SecondObj $s) 
    { 
     $s->TestMethod(); 
    } 
} 

和測試文件:

class PrimaryObj1_test extends PHPUnit_Framework_TestCase 
{ 
    private $primaryObj; 
    function setUp() 
    { 
     $this->primaryObj = new PrimaryObj1(); 
    } 
    function testDoNothing() 
    { 
     $secondObj = $this->getMock('SecondObj'); 
     $secondObj->expects($this->once()) 
        ->method("TestMethod"); 
     $this->primaryObj->doNothing($secondObj); 
    } 
} 

(一個測試每個虛擬類的文件,其中除了類名以外的所有內容都是相同的)。

當我運行PHPUnit的,這就是我得到:

Running Tests/PrimaryObj1_test.php 
1) PrimaryObj1_test::testDoNothing 
Expectation failed for method name is equal to <string:TestMethod> when invoked 1 time(s). 
Method was expected to be called 1 times, actually called 0 times. 

Running Tests/PrimaryObj2_test.php 
Fatal error: Call to undefined method Mock_SecondObj_99c898e7::TestMethod() in PrimaryObj2.php on line 5 

所以首先它是瘋了,它沒有調用預期的方法,但後來當我做生氣的原因是不確定的。我不能贏。我認爲這就是爲什麼我仍然單身...

任何想法,爲什麼這可能會發生?

+0

顯示代碼「SecondObj」 – hek2mgl 2013-05-01 18:57:27

+0

SecondObj僅作爲模擬存在。它沒有代碼或類聲明 – baiano 2013-05-01 19:03:21

+0

AFAIK嘲笑的類必須存在 – hek2mgl 2013-05-01 19:04:47

回答

0

我收到了電子郵件清單服務答覆。這條線:

$secondObj = $this->getMock('SecondObj'); 

應該是:

$secondObj = $this->getMock('SecondObj', array('TestMethod')); 

一旦我作出改變它的工作如預期。