7

如何重置 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');
4

1 回答 1

7

通过更多调查,您似乎只需再次调用 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');

感谢这个答案,它有助于 $this->at() 和 $this->exactly()

于 2012-04-27T01:35:15.210 回答