I’m currently developing unit tests with phpunit, and symfony 5. On a previous job using behat, we were able to reload the database only for the tests having a specific tag. I’d like to do something similar. I know there is the setUp() method and the @before annotation, but they don’t let me do thing for some tests and not others…
Ideally, I’d like to have a @reloadBase annotation to put on the test methods that are targetted by this, which would be bound to a reloadBase() method or something like; or at least something similar, but so far I couldn’t come up with a way to do it.
I guess there is the possibility to put those tests in a separate file which would have a setUp method doing so, but that’s not so great, I’d like to keep my current file organization…
Any ideas ? Thank you
Advertisement
Answer
Here are two ideas:
Trait/Base Class
Create a trait or a common base class with a method that does all the reloading stuff. Use the trait or extend the base class and call it just in the methods that need the reload.
Extension
Implement an extension. The BeforeTestHook
will be called for each test with a string consisting of the class and method name. You can either use an annotation reader (e.g. Doctrine’s) or use reflection and parse the doc block yourself to check whether the @reloadBase
annotation exists on that method.