鉴于以下课程:
Other = $Other; } public function query () { $params = array( 'key1' => 'Value 1' , 'key2' => 'Value 2' ); $this->Other->post($params); } }
而这个测试用例:
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->arrayHasKey('keyname');
方法存在,但其名称是assertArrayHasKey
:
// In your PHPUnit test method $hi = array( 'fr' => 'Bonjour', 'en' => 'Hello' ); $this->assertArrayHasKey('en', $hi); // Succeeds $this->assertArrayHasKey('de', $hi); // Fails
代替创建可重用的约束类,我能够使用PHPUnit中的现有回调约束来声明数组键的值.在我的用例中,我需要在模拟方法的第二个参数中检查数组值(MongoCollection :: ensureIndex(),如果有人好奇的话).这是我想出的:
$mockedObject->expects($this->once()) ->method('mockedMethod') ->with($this->anything(), $this->callback(function($o) { return isset($o['timeout']) && $o['timeout'] === 10000; }));
该回调约束预计它的构造函数调用,和评估过程中简单地调用它.断言根据callable是返回true还是false来传递或失败.
对于一个大型项目,我当然建议创建一个可重用的约束(如上面的解决方案)或请求将PR#312合并到PHPUnit中,但这样做可以满足一次性需求.很容易看出回调约束如何对更复杂的断言有用.
我最终创建了自己的约束类,基于属性1
constraint = $constraint; $this->arrayKey = $arrayKey; } /** * 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 */ public function evaluate($other) { if (!array_key_exists($this->arrayKey, $other)) { return false; } $this->value = $other[$this->arrayKey]; return $this->constraint->evaluate($other[$this->arrayKey]); } /** * @param mixed $other The value passed to evaluate() which failed the * constraint check. * @param string $description A string with extra description of what was * going on while the evaluation failed. * @param boolean $not Flag to indicate negation. * @throws PHPUnit_Framework_ExpectationFailedException */ public function fail($other, $description, $not = FALSE) { parent::fail($other[$this->arrayKey], $description, $not); } /** * Returns a string representation of the constraint. * * @return string */ public function toString () { return 'the value of key "' . $this->arrayKey . '"(' . $this->value . ') ' . $this->constraint->toString(); } /** * Counts the number of constraint elements. * * @return integer */ public function count () { return count($this->constraint) + 1; } protected function customFailureDescription ($other, $description, $not) { return sprintf('Failed asserting that %s.', $this->toString()); }
它可以像这样使用:
... ->with(new Test_Constraint_ArrayHas($this->equalTo($value), $key));