Reu*_*ben 5 php phpunit soap unit-testing mocking
如何重置 PHPUnit Mock 的 expects()?
我有一个 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');
Run Code Online (Sandbox Code Playgroud)
通过更多的调查,您似乎只需再次调用 expect() 即可。
但是,该示例的问题在于 $this->once() 的用法。在测试期间,无法重置与 expects() 关联的计数器。为了解决这个问题,你有几个选择。
第一个选项是忽略它被 $this->any() 调用的次数。
第二个选项是使用 $this->at($x) 来定位调用。请记住,$this->at($x) 是模拟对象被调用的次数,而不是特定的方法,并且从 0 开始。
在我的具体示例中,由于模拟测试两次都是相同的,并且预计只会调用两次,因此我也可以使用 $this->exactly(),只有一个 expects() 语句。IE
$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');
Run Code Online (Sandbox Code Playgroud)
这个答案对 $this->at() 和 $this->exactly() 有帮助