2012-04-24 5 views
4

PHPUnit Mockのexpects()をリセットするにはどうすればよいですか?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()の使用です。テストの間、expects()に関連付けられたカウンタはリセットできません。これに対処するには、いくつかのオプションがあります。

最初のオプションは、$ this-> any()で呼び出される回数を無視することです。

2番目のオプションは、$ this-> at($ x)を使用して呼び出しをターゲットにすることです。 $ this-> at($ x)は特定のメソッドではなく、モックオブジェクトが呼び出される回数です。

私の具体的な例では、モックテストは同じ2回だけ呼び出されると予想されますが、私は$ this-> exactly()も使用できますが、expects()文は1つしかありません。即ち

$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()

関連する問題