|
1 |
| -# phpunit-service-create-trait |
| 1 | +# PHPUnit Service Create Trait |
2 | 2 | A helper trait for PHPUnit 10+ for easier creation of services with dependencies in unit testing
|
| 3 | + |
| 4 | +## Usage |
| 5 | + |
| 6 | +In any of your PHPUnit test cases simply |
| 7 | + |
| 8 | +```php |
| 9 | +class MyTestCase extends \PHPUnit\Framework\TestCase { |
| 10 | + use \Pkly\ServiceMockHelperTrait; |
| 11 | + |
| 12 | + private AnyClass $service; |
| 13 | + |
| 14 | + public function setUp(): void { |
| 15 | + $this->service = $this->createRealMockedServiceInstance(AnyClass::class); |
| 16 | + } |
| 17 | + |
| 18 | + public function testSomething(): void |
| 19 | + { |
| 20 | + $mock = $this->createMock(MyEntity::class); |
| 21 | + |
| 22 | + $this->getMockedService(EntityManagerInterface::class) |
| 23 | + ->expects($this->once()) |
| 24 | + ->method('delete') |
| 25 | + ->with($mock); |
| 26 | + |
| 27 | + $this->service->deleteSomething($mock); |
| 28 | + } |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +Any dependencies in the constructor as well as methods marked with Symfony's `#[Required]` attribute will be automatically plugged in with mocks. |
| 33 | +This allows you to write complex tests without wasting time updating your construct calls each time you modify something. |
| 34 | + |
| 35 | +### Okay, but what if I need to use something custom? |
| 36 | + |
| 37 | +Simply assign the proper parameter name in either `$constructor` or `$required` in the appropriate methods. |
| 38 | +That will use your object instead of creating one for you, keep in mind you cannot retrieve it via `$this->getMockedService()`. |
| 39 | + |
| 40 | +### Partial objects? |
| 41 | + |
| 42 | +Sure, works the same, just use `createRealPartialMockedServiceInstance` instead of `createRealMockedServiceInstance`, in that case you must |
| 43 | +also specify the methods to override in your mock. Returned instance is `T&MockObject`. |
| 44 | + |
| 45 | +### Tests? More examples? |
| 46 | + |
| 47 | +I'll add them shortly, for now this code is being used thoroughly in a few of the projects I work at and I grew tired of updating it |
| 48 | +across multiple repositories. It's also very simple, so I doubt anyone is going to complain. |
| 49 | + |
| 50 | +### Feature requests? |
| 51 | + |
| 52 | +Sure, hit me up with an issue if you wish. |
0 commit comments