【问题标题】:How to reset a Mock Object with PHPUnit如何使用 PHPUnit 重置模拟对象
【发布时间】:2012-05-05 08:05:28
【问题描述】:

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

【问题讨论】:

    标签: php unit-testing soap mocking phpunit


    【解决方案1】:

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

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

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

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

    在我的具体例子中,因为模拟测试两次都是一样的,并且只期望被调用两次,我也可以使用 $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()

    【讨论】:

      猜你喜欢
      • 2014-11-14
      • 2014-08-23
      • 2011-03-09
      • 1970-01-01
      • 2021-10-31
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      相关资源
      最近更新 更多