gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:08:38 26 4
gpt4 key购买 nike

如何为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com