2012-04-17 120 views
4

從谷歌模擬的背景來看,我很驚訝這不起作用,除非我做錯了。PHPUnit模擬多種期望

我只是想確保一個方法是從未調用一個特定的類類型,但可能需要進行其他類類型。因此,這裏是我的代碼,說明我想要的東西:

$this->entityManagerMock 
     ->expects($this->any()) 
     ->method('persist'); 
$this->entityManagerMock 
    ->expects($this->never()) 
    ->method('persist') 
    ->with($this->isInstanceOf('MySpecificClass')); 

現在我得到類似這樣的消息:

Doctrine\ORM\EntityManager::persist(DifferentClassType Object (...)) was not expected to be called. 

當我想到,第一個期望來處理它。

我試過,但結果是一樣的:

$this->entityManagerMock 
     ->expects($this->any()) 
     ->method('persist') 
     ->with($this->anything()); 
$this->entityManagerMock 
    ->expects($this->never()) 
    ->method('persist') 
    ->with($this->isInstanceOf('MySpecificClass')); 

這是PHPUnit中使用嘲笑我的第一次,但在我看來,with被打破和/或沒有用處。我知道現在大多數網絡開發人員都使用TDD,所以必須有更好的方法來實現這一點。

回答

2

作爲一種變通,你可以使用returnCallback

$this->entityManagerMock 
    ->expects($this->any()) 
    ->method('persist') 
    ->will($this->returnCallback(function ($object) { 
     self::assertNotInstanceOf('MySpecificClass', $object); 
    })); 
+0

我想這是不是一個壞主意,因爲斷言還測試它,我是不是即使使用'will'。謝謝,雖然我希望上面的代碼仍然可以工作,但現在我會接受。 – Matt 2012-04-21 16:46:46