I have refactored some of my controllers to use dependency injection via property injection as recommended in the "best practices":
final class ZebraController extends Controller
{
/**
* @Inject
* @var AnimalClientInterface
*/
private $animalsRestClient;
public function fetchAllZebras(ServerRequestInterface $req): ResponseInterface {
// ...
}
}
My PHP-DI configuration is configured to inject an instance of the AnimalClient
object for AnimalClientInterface
, which is fine in implementation code as there is only 1 real AnimalClient
.
In my unit test I need to inject a MockZebraClient
into this property. I cannot simply configure it like I do for the AnimalClient
because other classes might be annotated similarly but need, for example, a MockTigerClient
for testing.
This is my unit test:
class ZebraControllerTest extends TestCase
{
/** @var ZebraController */
protected $object;
public function testFetchAllZebras(): void {
// assertions here
}
}
I think that using the injectOn
method is the correct way to approach this problem but I don't know how to configure the container to choose the correct mock object for the correct test.
Constructor injection isn't possible due to the legacy code structure. All the controllers in the application would need to be refactored to use DI in order to change the constructor of Controller
.