Using Spy Object in PHPUnit?

Matt - sanemat picture Matt - sanemat · Feb 7, 2011 · Viewed 7.3k times · Source

How can I use Spy Object in PHPUnit? You can call object in imitation on, and after you can assert how many times it called. It is Spy.

I know "Mock" in PHPUnit as Stub Object and Mock Object.

Answer

Gordon picture Gordon · Feb 7, 2011

You can assert how many times a Mock was called with PHPUnit when doing

    $mock = $this->getMock('SomeClass');
    $mock->expects($this->exactly(5))
         ->method('someMethod')
         ->with(
             $this->equalTo('foo'), // arg1
             $this->equalTo('bar'), // arg2
             $this->equalTo('baz')  // arg3
         );

When you then call something in the TestSubject that invokes the Mock, PHPUnit will fail the test when SomeClass someMethod was not called five times with arguments foo,bar,baz. There is a number of additional matchers besides exactly.

In addition, PHPUnit as has built-in support for using Prophecy to create test doubles since version 4.5. Please refer to the documentation for Prophecy for further details on how to create, configure, and use stubs, spies, and mocks using this alternative test double framework.