2012-04-24 159 views
4

如何重置PHPUnit模擬的期望()?如何用PHPUnit重置模擬對象

我有一個模擬的SoapClient,我想在測試中多次調用,重置每次運行的期望。

$soapClientMock = $this->getMock('SoapClient', array('__soapCall'), array($this->config['wsdl'])); 
$this->Soap->client = $soapClientMock; 

// call via query 
$this->Soap->client->expects($this->once()) 
    ->method('__soapCall') 
    ->with('someString', null, null) 
    ->will($this->returnValue(true)); 

$result = $this->Soap->query('someString'); 

$this->assertFalse(!$result, 'Raw query returned false'); 

$source = ConnectionManager::create('test_soap', $this->config); 
$model = ClassRegistry::init('ServiceModelTest'); 

// No parameters 
$source->client = $soapClientMock; 
$source->client->expects($this->once()) 
    ->method('__soapCall') 
    ->with('someString', null, null) 
    ->will($this->returnValue(true)); 

$result = $model->someString(); 

$this->assertFalse(!$result, 'someString returned false'); 

回答

4

隨着多一點調查,似乎你只是再次調用expect()。

但是,這個例子的問題是使用$ this-> once()。在測試期間,與期望()相關的計數器不能被重置。爲了解決這個問題,你有幾個選擇。

第一個選項是忽略使用$ this-> any()調用的次數。

第二個選項是使用$ this-> at($ x)作爲目標。記住$ this-> at($ x)是模擬對象被調用的次數,而不是特定的方法,並且從0開始。

以我的具體示例,因爲模擬測試兩次都是相同的,並且只希望被調用兩次,我也可以使用$ this-> exactly(),只有一個expect()語句。即

$soapClientMock = $this->getMock('SoapClient', array('__soapCall'), array($this->config['wsdl'])); 
$this->Soap->client = $soapClientMock; 

// call via query 
$this->Soap->client->expects($this->exactly(2)) 
    ->method('__soapCall') 
    ->with('someString', null, null) 
    ->will($this->returnValue(true)); 

$result = $this->Soap->query('someString'); 

$this->assertFalse(!$result, 'Raw query returned false'); 

$source = ConnectionManager::create('test_soap', $this->config); 
$model = ClassRegistry::init('ServiceModelTest'); 

// No parameters 
$source->client = $soapClientMock; 

$result = $model->someString(); 

$this->assertFalse(!$result, 'someString returned false'); 

Kudos for this answer that assisted with $this->at() and $this->exactly()