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を実装して保存する独自のクラスを作成しますか?FooInterfacepersist

4

2 に答える 2

1

もう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 に答える
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 に答える