-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Replace DIC services with mocks in tests #29109
Comments
You can achieve the same with proper configuration by using suffixes with env names. |
Not sure what you mean by that exactly, but if you're referring to env configs (e.g. |
That requirement is actually incompatible with having an optimized container; that's why it doesn't work. Private services can be inlined, and any reference to them are optimized out. As the message suggests, you should make the service public if you really want to do this. Closing as there is no bug here. Thanks for reporting. |
But I only want it to be public, or more accurately: replaceable, in tests. |
Can you try creating a public alias, then setting the service using that alias in your test? |
@nicolas-grekas solution works like a charm. ❤️ |
But it's really cumbersome to make an alias for every service we want to mock..... Isn't there a way to make all services in container public for testing purposes ? |
@bcastagna You can change the service.yaml in your project to replace your services with a mocked one from your tests or if you want them to be public, you can set it there too. Example: I have a controller action where the Finder Component of Symfony searches in a specific directory on the mashine for some config files. In tests, these directories may not exists because my application is bound to another app on the same mashine. To build better and more independent tests, I want to mock that Finder and replace it with a Finder, that has been modified so that the directory is one in the tests folders. service_test.yaml
MyTest.php
ModifiedTestFinder.php
Alternatively, you can overwrite the Symfony Finder for all tests. service_test.yaml
But be aware, that modifying the container during tests can lead to unexpected behavior during excecution of your tests. This can lead to a diverged behavior between prod and test environment, if you are not careful. It depends on how good you manage your tests. |
Good new, it is happening: #48938, we can probably close this 4+ years old issue. |
...but it is closed... and has been for almost 5 years... Nevertheless, thanks for bringing it to my attention 👍🏻 |
Oh right, the purple color made me think it was still open, sorry |
Description
Since 4.1 we can access private services in tests but we cannot substitute any services with mocks, as may be required by some testing strategies.
Example
The text was updated successfully, but these errors were encountered: