如何重置PHPUnit Mock的expected()?
我想在测试中多次调用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');
答案 0 :(得分:4)
通过更多的调查,你似乎只是再次调用expect()。
但是,该示例的问题是使用$ this-> once()。在测试期间,与expected()关联的计数器无法重置。为了解决这个问题,你有几个选择。
第一个选项是忽略使用$ this-> any()调用它的次数。
第二个选项是使用$ this-> at($ x)来定位呼叫。请记住$ this-> at($ x)是模拟对象被调用的次数,而不是特定的方法,并从0开始。
使用我的具体示例,因为模拟测试两次都是相同的,并且只能被调用两次,所以我也可以使用$ this-> exact(),只有一个expected()语句。即。
$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()