|
| 1 | +# bigcommerce/test-injector |
| 2 | + |
| 3 | +Auto-mocking test Dependency Injector component |
| 4 | + |
| 5 | +Will automatically mock all injected dependencies of an object using the BigCommerce Injector. This allows objects to be |
| 6 | +refactored to have dependencies removed or new ones added without needing to rebuild all the mock definitions or modify |
| 7 | +many tests, making decoupled DI driven development much easier. |
| 8 | + |
| 9 | +Mocks can be configured with expectations by calling getMock(CLASS_NAME) on the TestInjector within your tests. This |
| 10 | +will return an ObjectProphecy object (a mock generated by Prophecy - the mocking library included in PHPUnit). |
| 11 | + |
| 12 | +A single mock instance is created per Fully Qualified Class Name, so if the object you're testing takes two of the same |
| 13 | +typed parameter, the same mock will be passed to both (so ensure your expectations are set appropriately). |
| 14 | + |
| 15 | +Construction Usage: |
| 16 | +```` |
| 17 | +// All constructor dependencies resolved through mocking |
| 18 | +$testObject = $testInjector->create(My\Test\Object::class); |
| 19 | +
|
| 20 | +// Parameter injection - will provide parameters either by type, name or position - otherwise resolve via mocking |
| 21 | +$testObject = $testInjector->create(My\Test\Object::class, [ |
| 22 | + "enabled" => true, // Named |
| 23 | + 7 => "fish", // Positional |
| 24 | + Logger::class => new Logger(), // Type |
| 25 | +]); |
| 26 | +```` |
| 27 | + |
| 28 | +Invocation usage |
| 29 | +```` |
| 30 | +// Call the method 'createUser' on an existing object |
| 31 | +$testObject = $testInjector->invoke($instanceOfThing, "createUser"); |
| 32 | +
|
| 33 | +// Parameter injection - will provide parameters either by type, name or position - otherwise resolve via mocking |
| 34 | +$testObject = $testInjector->invoke($instanceOfThing, "createUser", [ |
| 35 | + "enabled" => true, // Named |
| 36 | + 7 => "fish", // Positional |
| 37 | + Logger::class => new Logger(), // Type |
| 38 | +]); |
| 39 | +```` |
| 40 | + |
| 41 | + |
| 42 | +For integration with your PHPUnit tests, see: [AutoMockingTest.php](src/AutoMockingTest.php) |
0 commit comments