【发布时间】:2010-12-02 00:26:57
【问题描述】:
给定以下类:
<?php
class Example {
private $Other;
public function __construct ($Other)
{
$this->Other = $Other;
}
public function query ()
{
$params = array(
'key1' => 'Value 1'
, 'key2' => 'Value 2'
);
$this->Other->post($params);
}
}
还有这个测试用例:
<?php
require_once 'Example.php';
require_once 'PHPUnit/Framework.php';
class ExampleTest extends PHPUnit_Framework_TestCase {
public function test_query_key1_value ()
{
$Mock = $this->getMock('Other', array('post'));
$Mock->expects($this->once())
->method('post')
->with(YOUR_IDEA_HERE);
$Example = new Example($Mock);
$Example->query();
}
如何验证$params(它是一个数组)并传递给$Other->post() 包含一个名为“key1”且值为“Value 1”的键?
我不想验证所有数组 - 这只是一个示例代码,在实际代码中,传递的数组有更多的值,我只想验证其中的一个键/值对。
我可以使用$this->arrayHasKey('keyname') 来验证密钥是否存在。
还有$this->contains('Value 1'),可以用来验证数组是否有这个值。
我什至可以将这两者与$this->logicalAnd 结合起来。但这当然不会产生预期的结果。
到目前为止,我一直在使用 returnCallback,捕获整个 $params,然后对其进行断言,但是也许还有另一种方法可以做我想做的事?
【问题讨论】:
-
$this->attribute(Constraint, value) 能够做我所追求的,但它不适用于数组。