在PHPUnit中声明数组equalTo,其中一些值为null

时间:2016-08-06 12:31:42

标签: php unit-testing phpunit associative-array

我所拥有的是一个看起来像这样的数组,它被传递给一个方法,如下所示:

$data = array(
    'stuff' => 'things',
    'otherstuff' => NULL,
    'morestuff' => NULL,
);
$object->doStuffWithArray($data);

所以我正在编写单元测试,我需要通过断言传递给它的参数来删除doStuffWithArray行为。所以我正在做的是这样的事情:

$object_mock->expects($this->once())
            ->with($this->equalTo(array(
                'stuff' => 'things',
                'otherstuff' => NULL,
                'morestuff' => NULL,
            )));

但这有点太严格了。如果值为NULL的字段根本不在数组中,我希望单元测试也通过。我有什么方法可以在PHPUnit中做到这一点吗?

1 个答案:

答案 0 :(得分:1)

使用回调函数,使用您需要的任何逻辑来确认数组是否有效。例如类似的东西:

$object_mock->expects($this->once())
    ->with($this->callback(function($arg){
        if ($arg == array(
            'stuff' => 'things',
            'otherstuff' => NULL,
            'morestuff' => NULL
        )) {
            return true;
        }

        if ($arg == array(
            'stuff' => 'things'
        )) {
            return true;
        }

        return false;
    })
);

请参阅https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects

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