在PHPUnit中使用Spy对象?

Mat*_*mat 6 php phpunit spy

如何在PHPUnit中使用Spy对象?您可以在模仿中调用对象,然后您可以断言它调用了多少次.这是间谍.

我知道PHPUnit中的"Mock"是Stub Object和Mock Object.

Gor*_*don 11

您可以断言在执行时使用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
         );
Run Code Online (Sandbox Code Playgroud)

当你在TestSubject中调用调用Mock的东西时,当SomeClass someMethod没有使用参数foo,bar,baz调用五次时,PHPUnit将无法通过测试.此外还有许多其他匹配器exactly.

此外,PHPUnit内置支持使用Prophecy从4.5版开始创建测试双精度.有关如何使用此备用测试双框架创建,配置和使用存根,间谍和模拟的更多详细信息,请参阅Prophecy文档.


lyt*_*yte 6

从传回的间谍$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]);
Run Code Online (Sandbox Code Playgroud)

我在某个阶段对此发表了博客条目:http : //blog.lyte.id.au/2014/03/01/spying-with-phpunit/

我不知道它在哪里记录(如果?),我发现它正在搜索PHPUnit代码...

  • 是我还是[不再是这种情况](https://github.com/sebastianbergmann/phpunit/blob/60c32c5b5e79c2248001efa2560f831da11cc2d7/src/Framework/TestCase.php#L1898-L1901)? (3认同)