在 PHPUnit 中断言数组 equalTo,某些值为 null
asserting array equalTo in PHPUnit with some values null
我有一个看起来像这样的数组,它被传递到一个方法中,如下所示:
$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 中做到这一点吗?
改用回调函数,使用您需要的任何逻辑来确认数组是否有效。例如类似于:
$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
"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."
我有一个看起来像这样的数组,它被传递到一个方法中,如下所示:
$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 中做到这一点吗?
改用回调函数,使用您需要的任何逻辑来确认数组是否有效。例如类似于:
$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
"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."