Why I choose mockery over phpunit-mock

Test doubles are not new thing for php developers. When it comes to mocking there are clear 3 choices at the moment, assuming that phpUnit is used for testing.

1. PhpUnit Mock (Default)
2. Mockery
3. Phrophesy

I have not got much experience with phrophesy. But it’s more a behavioural testing tool for bdd style of development than a testing tool.

Everzet, the man himself, provides amazing little blog about it here. Please read.

Among remaining two, I use Mockery for few reasons.

1. Easy to mock

Mockery::mock(‘My\Amazing\Class’);

or

Mockery::mock(‘My\Amazing\Interface’);

2. Mocking with Chain and Fluent Interface

I will take an example from Mockery doc.

Code: $object->foo()->bar()->selfDestruct();
MockeryMock: $mock->shouldReceive('foo->bar->selfDestruct')->andReturn('Ten!');

A real life example would be:

if $this->securityContext->getToken()->isAuthenticated(){}

How do you do this with phpUnit?

i) You mock bar.

ii) Mock foo

I assume it uses DI in both levels

iii) Mock $object

3. Calling of a method more than once with different parameters

Lets take an example of code below.

$object->addSomething(‘thing 1′)
->addSomething(‘thing2);

With Mockery:
$mock->shouldReceive(‘addSomething’)
->with(‘thing1)
->andReturn($mock);
$mock->shouldReceive(‘addSomething’)
->with(‘thing2)
->andReturn($object);

WithPhpUnit:
You get error if you stub a method twice. Umm…..

4. Mocking Final Methods Proxy

Read here.

Swahaa!! for now!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>