php - 如何使用 PHPUnit 重置模拟对象

标签 php unit-testing soap mocking phpunit

如何为 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');

最佳答案

经过更多调查,您似乎只是再次调用了 expect()。

然而,这个例子的问题在于 $this->once() 的使用。在测试期间,无法重置与 expects() 关联的计数器。为了解决这个问题,您有几个选择。

第一个选项是忽略它被 $this->any() 调用的次数。

第二个选项是使用 $this->at($x) 来定位调用。请记住 $this->at($x) 是模拟对象被调用的次数,而不是特定方法,并且从 0 开始。

以我的具体例子来说,因为mock test两次都是一样的,预计只会被调用两次,所以我也可以使用$this->exactly(),只有一个expects()语句。即

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

关于php - 如何使用 PHPUnit 重置模拟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302102/

相关文章:

php - PEAR 包通常安装在哪里?

ruby-on-rails - spec 和 test 文件夹之间的区别

php - 网站需要永远加载然后我得到 "Uncaught SoapFault exception"

java - Maven 使用关键字 "Test"运行所有测试

java - 如何将java.util.Date转换为soap支持的日期格式 "yyyy-MM-dd' T'HH :mm:ss"with zone id

java - 使用 CXF 附加 SOAP 处理程序

php - android 中图像不显示

php - Magento 不显示完整的产品名称

javascript - 如何将默认文本添加到 HTML <select>?

unit-testing - 初始化函数中断单元测试