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

对于下面的代码,

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

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

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

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

function ($config){
    $this->assertFalse(isset($config['shouldnothere']));
    $this->assertTrue($config['object']->isValidValue());
}
你可以使用 – > with($this-> callback())并传入一个闭包来对参数执行更复杂的断言.

PHPUnit Docs

The callback() constraint can be used for more complex argument
verification. This constraint takes a PHP callback as its only
argument. The PHP callback will receive the argument to be verified as
its only argument and should return TRUE if the argument passes
verification and FALSE otherwise.

Example 10.13: More complex argument verification

getMock(‘Observer’, array(‘reportError’));

06000

所以你的测试将成为:

$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([]));
相关文章
相关标签/搜索