如何在 PHPUnit 中使用 Spy 对象? 您可以模仿调用对象,然后可以断言它调用了多少次。 这是间谍。
我知道 PHPUnit 中的“Mock”为 Stub 对象和 Mock 对象。
您可以断言在执行操作时使用 PHPUnit 调用了 Mock 多少次
$mock = $this->getMock('SomeClass');
$mock->expects($this->exactly(5))
->method('someMethod')
->with(
$this->equalTo('foo'), // arg1
$this->equalTo('bar'), // arg2
$this->equalTo('baz') // arg3
);
当您在 TestSubject 中调用调用 Mock 的某些内容时,如果未使用参数 foo、bar、baz 调用 SomeClass someMethod 五次,PHPUnit 将导致测试失败。除了 exactly
此外,PHPUnit 自 4.5 版本以来内置支持使用 Prophecy 创建测试替身。请参阅 Prophecy 的文档,了解有关如何使用此替代测试双重框架创建、配置和使用存根、间谍和模拟的更多详细信息。
$this->any()
返回的间谍,你可以像这样使用它:
$foo->expects($spy = $this->any())->method('bar');
$foo->bar('baz');
$invocations = $spy->getInvocations();
$this->assertEquals(1, count($invocations));
$args = $invocations[0]->arguments;
$this->assertEquals(1, count($args));
$this->assertEquals('bar', $args[0]);
我在某个阶段发表了一篇关于此的博客文章:http://blog.lyte.id.au/2014/03/01/spying-with-phpunit/
我不知道它在哪里(如果?)有记录,我发现它通过 PHPUnit 代码搜索......
$foo->expects($spy = $this->any())->method('bar');
$foo->bar('baz');
$invocations = $spy->getInvocations();
$this->assertEquals(1, count($invocations));
$args = $invocations[0]->getParameters();
$this->assertEquals(1, count($args));
$this->assertEquals('bar', $args[0]);
$mock = $this->getMock('SomeClass');
$mock->expects($spy = $this->any())
->method('someMethod')
->with(
$this->equalTo('foo'), // arg1
$this->equalTo('bar'), // arg2
$this->equalTo('baz') // arg3
);
如果您只是想随叫随到:
self::assertTrue($spy->hasBeenInvoked());
如果是多个:
$this->assertEquals(5, count($spy->getInvocations()));