2

我写了一个基本上看起来像这样的方法:

public function collectData($input, FooInterface $foo) {
   $data = array();
   $data['products']['name'] = $this->some_method();
   if(empty($input['bar'])) {
       $data['products']['type'] = "Baz";
   }
   // hundreds of calls later
   $foo->persist($data);
}

现在我想对该collectData方法进行单元测试,以检查是否$data为某些输入设置了值。对于对象参数,我通常会使用这样的模拟:

$mock = $this->getMock('FooInterface');
$mock->expects($this->once())
             ->method('persist')
             ->with($this->identicalTo($expectedObject));

但是我将如何测试某些嵌套数组键(例如,如果$data['products']['prices']['taxgroup']是 1),而忽略数组中可能存在的所有其他键?PHPUnit 或 Mockery 是否提供此类检查?或者他们可以很容易地扩展以提供这样的检查吗?

还是做我现在正在做的事情更好:创建我自己的FooClassMock类来实现FooInterface并将数据存储在persist调用中?

4

2 回答 2

1

事实证明,有一种方法——我可以创建自己的约束类。之后,很容易:

$constraint = new NestedArrayConstraint(
    array('products', 'prices', 'taxgroup'),
    $this->equalTo(1)
);
$mock = $this->getMock('FooInterface', array('persist'));
$mock->expects($this->once())
             ->method('persist')
             ->with($constraint);
于 2013-03-08T08:56:04.180 回答
1

您还有一个选择,但前提是您使用 PHPUnit >= 3.7。有一个回调断言,你可以像这样使用它:

$mock = $this->getMock('FooInterface', array('persist');
$mock->expects($this->once())
         ->method('persist')
         ->with($this->callback(function($object) {
             // here you can do your own complex assertions

             return true|false;
         }));

这里有更多细节:

https://github.com/sebastianbergmann/phpunit/pull/206

于 2013-03-08T09:21:34.633 回答