Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spy Object in PHPUnit?

Tags:

php

phpunit

spy

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.

like image 521
Matt - sanemat Avatar asked Feb 07 '11 16:02

Matt - sanemat


People also ask

How to mock method in PHPUnit?

PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.

What is stub in PHPUnit?

Stub. Stubs are used with query like methods - methods that return things, but it's not important if they're actually called. $stub = $this->createMock(SomeClass::class); $stub->method('getSomething') ->willReturn('foo'); $sut->action($stub);


2 Answers

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.

like image 175
Gordon Avatar answered Oct 31 '22 05:10

Gordon


There's a spy returned from $this->any(), you can use it something like:

$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]);

I put up a blog entry about this at some stage: http://blog.lyte.id.au/2014/03/01/spying-with-phpunit/

I have no idea where (if?) it's documented, I found it searching through PHPUnit code...

like image 45
lyte Avatar answered Oct 31 '22 04:10

lyte