PHPUnit:将参数传递给mock对象时置位参数

sca*_*pus 16 php phpunit unit-testing

对于下面的代码,

$mockObject->expects($this->at(0))
           ->method('search')
           ->with($searchConfig)
           ->will($this->returnValue([]));
Run Code Online (Sandbox Code Playgroud)

该行将自动断言,当它调用方法时,search它必须包含$searchConfig参数.在这种情况下,我们必须提供完全匹配,$searchConfig但有时如果它是一个数组或一个对象很难.

是否有任何可能的方法让PHPUnit调用某个特定的方法断言它包含参数传递方法我们想要?

例如,我可以创建闭包函数来断言如下,而不是使用->with()方法

function ($config){
    $this->assertFalse(isset($config['shouldnothere']));
    $this->assertTrue($config['object']->isValidValue());
}
Run Code Online (Sandbox Code Playgroud)

Sch*_*eis 35

您可以使用->with($this->callback())并传入一个闭包来对参数执行更复杂的断言.

来自PHPUnit文档

callback()约束可用于更复杂的参数验证.此约束将PHP回调作为其唯一参数.PHP回调将接收要验证的参数作为其唯一参数,如果参数通过验证则返回TRUE,否则返回FALSE.

例10.13:更复杂的参数验证

getMock('Observer',array('reportError'));

    $observer->expects($this->once())
             ->method('reportError')
             ->with($this->greaterThan(0),
                    $this->stringContains('Something'),
                    $this->callback(function($subject){
                      return is_callable(array($subject, 'getName')) &&
                             $subject->getName() == 'My subject';
                    }));

    $subject = new Subject('My subject');
    $subject->attach($observer);

    // The doSomethingBad() method should report an error to the observer
    // via the reportError() method
    $subject->doSomethingBad();
} } ?>
Run Code Online (Sandbox Code Playgroud)

所以你的测试将成为:

$mockObject->expects($this->at(0))
->method('search')
->with($this->callback(
    function ($config){
        if(!isset($config['shouldnothere']) && $config['object']->isValidValue()) {
            return true;
        }
        return false;
    })
->will($this->returnValue([]));
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,如果你的函数有超过1个参数,那么this-> callback()只适用于第一个参数.所以你需要为每个参数定义一个回调 (5认同)
  • 在验证多个参数时,我总是忘记使用`return true`. (2认同)