如何使用PHPUnit重置Mock对象

12

如何重置PHPUnit Mock的expects()?

我有一个SoapClient的Mock,我想在测试中多次调用它,每次运行时重置期望。

$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');
2个回答

10

通过更深入的调查,似乎只需要再次调用expect()。

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

第一种选择是使用 $this->any() 来忽略它被调用的次数。

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

对于我的特定示例,因为 mock 测试两次都是相同的,并且仅期望被调用两次,所以我也可以使用 $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');

感谢这个回答帮助解决了$this->at()和$this->exactly()的问题。


0

您可以这样清除模拟:

// Verify first
$mock->mockery_verify();
        
// and then overwrite with empty expectation directors 
foreach(array_keys($mock->mockery_getExpectations()) as $method) {
    $mock->mockery_setExpectationsFor($method, new Mockery\ExpectationDirector($method, $mock));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接