How can I mock an autowired service to symfony controller in phpunit functional tests? How can I mock an autowired service to symfony controller in phpunit functional tests? symfony symfony

How can I mock an autowired service to symfony controller in phpunit functional tests?


The short answer is you don't.

The WebTestCase is intended for higher level tests, sometimes called Functional or Integration tests. They are intended to use the actual services or appropriate test alternatives, e.g. a SQLite database for tests instead of MySQL or a Paypal-sandbox instead of the production service. If you want to test a service and replace its dependencies with a mock or stub you should be writing a Unit Test instead.

If you want to replace your service with a dummy implementation, e.g. one that always returns the same id or a hash based on the input, you can replace the alias in the container configuration in your config/services_test.yaml that will be used whenever your application uses the test app environment (which the WebTestCase by default does). You could also try changing the container during runtime, but because Symfony compiles the container and then freezes it, i.e. does not allow any changes to the container, it might be tricky and is not really recommended.

As a further reference Symfony 4.1 provides a container with all services, including private ones, exposed: https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testingThis will likely not help in your case, but it shows how you can interact with the service container in WebTestCase-tests.