加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何使用PHPUnit重置Mock对象

发布时间:2020-12-13 17:11:49 所属栏目:PHP教程 来源:网络整理
导读:如何重置 PHPUnit Mock的expected()? 我有一个模拟SoapClient,我想在测试中多次调用,重置每次运行的期望. $soapClientMock = $this-getMock('SoapClient',array('__soapCall'),array($this-config['wsdl']));$this-Soap-client = $soapClientMock;// call v
如何重置 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)
    ->will($this->returnValue(true));

$result = $model->someString();

$this->assertFalse(!$result,'someString returned false');

解决方法

通过更多的调查,你似乎只是再次调用expect().

但是,该示例的问题是使用$this-> once().在测试期间,与expected()关联的计数器无法重置.为了解决这个问题,你有几个选择.

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

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

根据我的具体示例,因为模拟测试两次都是相同的,并且只能被调用两次,所以我也可以使用$this-> exact(),只有一个expected()语句.即

$soapClientMock = $this->getMock('SoapClient',array($this->config['wsdl']));
$this->Soap->client = $soapClientMock;

// call via query
$this->Soap->client->expects($this->exactly(2))
    ->method('__soapCall')
    ->with('someString',$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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读