我想在phpunit中创建一个模拟器,以验证是否正在使用正确的参数调用函数。该参数是一个关联数组,包含三个元素,两个已知,一个未知:
array( 'objecttype' => 'thing', 'objectid'=> 2, 'tstamp' => [some tstamp here] )
由于我不知道确切的完整数组,我不能使用equalTo约束。我可以使用logicalAnd,contains和arrayHasKey的组合来实现这一目标,但这似乎非常hacky,并且,如果由于某些疯狂的原因我的键和值混淆了,它将无法捕获错误。有没有更好的方法来解决这个问题?
答案 0 :(得分:3)
这是一个快速而又脏的自定义约束,用于检查传递的数组是否至少包含给定的条目(键/值对)。将它添加到您的自定义测试框架或PHPUnit fork。请注意,它使用==
相等,以便'5'
的键/映射匹配5
。
class ArrayHasEntries extends PHPUnit_Framework_Constraint
{
/**
* @var array
*/
protected $array;
/**
* @param array $array
*/
public function __construct(array $array)
{
$this->array = $array;
}
/**
* Evaluates the constraint for parameter $other. Returns TRUE if the
* constraint is met, FALSE otherwise.
*
* @param mixed $other Value or object to evaluate.
* @return bool
*/
protected function matches($other)
{
foreach ($this->array as $key => $value) {
if (!array_key_exists($key, $other) || $other[$key] != $value) {
return false;
}
}
return true;
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
return 'has the entries ' . PHPUnit_Util_Type::export($this->array);
}
/**
* Returns the description of the failure
*
* The beginning of failure messages is "Failed asserting that" in most
* cases. This method should return the second part of that sentence.
*
* @param mixed $other Evaluated value or object.
* @return string
*/
protected function failureDescription($other)
{
return 'an array ' . $this->toString();
}
}