In this article I would like share with you a little experience with:
Symfony Dependence Injaction
This is an example of very easy controller.
$this->container->getParameter("do_stuff") is a boolean parameter that enable or disable a feature, How can I test this snippet?
I can try to write a functional test but in my opinion is easier write a series of unit tests with PhpUnit to validate my expectations.
If do_stuff parameter is false function get by my container will be call zero times
If do_stuff parameter is true function get by my container will be call one times
This is my first expetection “If do_stuff param is true I call stuff.service”.
In this controller I use a few objects, Http\Request, Container and stuff.service in this example is a Some\Stuff class.
In the first step I have created one mock for each object.
In the second step I have written my first expetctation, “Call only one time function getParameter from $container with argument do_stuff and it returns true”.
Thanks at this definitions I know that there will be another effect, my action will call only one time $container->get("stuff.service") and it will be return an Some\Stuff object.
The second test that we can write is “if do_stuff is false $contaner->get("stuff.service") it will not be called.