2008-11-22 70 views
53

第二個參數,這是我有:如何測試在PHPUnit的mock對象

$observer = $this->getMock('SomeObserverClass', array('method')); 
$observer->expects($this->once()) 
     ->method('method') 
     ->with($this->equalTo($arg1)); 

但這種方法應該採取兩個參數。我只測試第一個參數是否正確傳遞(如$ arg1)。

如何測試第二個參數?

回答

85

我認爲要做到這一點的方法是:

$observer->expects($this->once()) 
    ->method('method') 
    ->with($this->equalTo($arg1),$this->equalTo($arg2)); 

或者

$observer->expects($this->once()) 
    ->method('method') 
    ->with($arg1, $arg2); 

如果您需要在第二個ARG執行不同類型的斷言,你能做到這一點,太:

$observer->expects($this->once()) 
    ->method('method') 
    ->with($this->equalTo($arg1),$this->stringContains('some_string')); 

如果您需要確保某些參數傳遞多個斷言,請使用logicalAnd()

$observer->expects($this->once()) 
    ->method('method') 
    ->with($this->logicalAnd($this->stringContains('a'), $this->stringContains('b'))); 
+1

幾周前我遇到了這個問題。使用: - > with($ this-> equalTo($ foo,$ bar) 爲我工作 – ieure 2008-12-13 22:40:32