Helpers to build PHPUnit mocks

Fund package maintenance!

1.4.0 2020-10-12 13:57 UTC

This package is auto-updated.

Last update: 2024-05-12 22:05:24 UTC


Helpers to build PHPUnit mock objects easily.

Total Downloads


This library is not a mocking library. It's just a few helpers to write the most common mocks more easily.

It doesn't reinvent anything and is not intended to cover every use case: only the most common ones.


$ composer require --dev mnapoli/phpunit-easymock

To be able to use EasyMock in your tests you must include the trait in your class:

class MyTest extends \PHPUnit\Framework\TestCase
    use \EasyMock\EasyMock;

    // ...


Here is what a very common PHPUnit mock looks like:

$mock = $this->createMock('My\Class');



Here is how to write it with EasyMock:

$mock = $this->easyMock('My\Class', [
    'sayHello' => 'Hello',

What if you want to assert that the method is called once (i.e. $mock->expect($this->once()))? Use spy() instead:

$mock = $this->easySpy('My\Class', [
    'sayHello' => 'Hello',


You can mock methods so that they return values:

$mock = $this->easyMock('My\Class', [
    'sayHello' => 'Hello',

Or so that they use a callback:

$mock = $this->easyMock('My\Class', [
    'sayHello' => function ($name) {
        return 'Hello ' . $name;

You can also have methods throw exceptions by providing an Exception instance:

$mock = $this->easyMock('My\Class', [
    'sayHello' => new \RuntimeException('Whoops'),

It is possible to call the mock() method again on an existing mock:

$mock = $this->easyMock('My\Class');

$mock = $this->easyMock($mock, [
    'sayHello' => 'Hello',

What if?

If you want to use assertions or other PHPUnit features, just do it:

$mock = $this->easyMock('My\Class', [
    'sayHello' => 'hello',


Mocks are plain PHPUnit mocks, nothing special here.


See the CONTRIBUTING file.


Released under the MIT license.