|
| 1 | +# PHPUnit EasyMock |
| 2 | + |
| 3 | +Helpers to build PHPUnit mock objects easily. |
| 4 | + |
| 5 | +[](https://travis-ci.org/mnapoli/PHP-DI) |
| 6 | +[](https://coveralls.io/r/mnapoli/PHP-DI?branch=master) |
| 7 | +[](https://scrutinizer-ci.com/g/mnapoli/PHP-DI/) |
| 8 | +[](https://packagist.org/packages/mnapoli/php-di) |
| 9 | +[](https://packagist.org/packages/mnapoli/php-di) |
| 10 | + |
| 11 | +## Why? |
| 12 | + |
| 13 | +This library is **not** a mocking library. It's just a few helpers to write the most common mocks more easily. |
| 14 | + |
| 15 | +It doesn't reinvent anything and is not intended to cover every use case: only the most common ones. |
| 16 | + |
| 17 | +## Installation |
| 18 | + |
| 19 | +```bash |
| 20 | +$ composer require --dev mnapoli/phpunit-easymock |
| 21 | +``` |
| 22 | + |
| 23 | +## Usage |
| 24 | + |
| 25 | +Here is what a very common PHPUnit mock looks like: |
| 26 | + |
| 27 | +```php |
| 28 | +// All these parameters to avoid calling the constructor |
| 29 | +$mock = $this->getMock('My\Class', array(), array(), '', false); |
| 30 | + |
| 31 | +$mock->expect($this->any()) |
| 32 | + ->method('sayHello') |
| 33 | + ->willReturn('Hello'); |
| 34 | +``` |
| 35 | + |
| 36 | +Yuck! |
| 37 | + |
| 38 | +Here is how to write it with EasyMock: |
| 39 | + |
| 40 | +```php |
| 41 | +$mock = EasyMock::mock('My\Class', array( |
| 42 | + 'sayHello' => 'Hello', |
| 43 | +)); |
| 44 | +``` |
| 45 | + |
| 46 | +### Features |
| 47 | + |
| 48 | +You can mock methods so that they return values: |
| 49 | + |
| 50 | +```php |
| 51 | +$mock = EasyMock::mock('My\Class', array( |
| 52 | + 'sayHello' => 'Hello', |
| 53 | +)); |
| 54 | +``` |
| 55 | + |
| 56 | +Or so that they use a callback: |
| 57 | + |
| 58 | +```php |
| 59 | +$mock = EasyMock::mock('My\Class', array( |
| 60 | + 'sayHello' => function ($name) { |
| 61 | + return 'Hello ' . $name; |
| 62 | + }, |
| 63 | +)); |
| 64 | +``` |
| 65 | + |
| 66 | +### What if? |
| 67 | + |
| 68 | +If you want to use assertions or other PHPUnit features, just do it: |
| 69 | + |
| 70 | +```php |
| 71 | +$mock = EasyMock::mock('My\Class', array( |
| 72 | + 'sayHello' => 'hello', |
| 73 | +)); |
| 74 | + |
| 75 | +$mock->expects($this->once()) |
| 76 | + ->method('sayGoodbye') |
| 77 | + ->willReturn('Goodbye'); |
| 78 | +``` |
| 79 | + |
| 80 | +Mocks are plain PHPUnit mocks, nothing special here. |
| 81 | + |
| 82 | +## Contributing |
| 83 | + |
| 84 | +See the [CONTRIBUTING](CONTRIBUTING.md) file. |
| 85 | + |
| 86 | +## License |
| 87 | + |
| 88 | +Released under the [MIT license](LICENSE). |
0 commit comments