jeudi 2 avril 2015

How to test a symfony2 embedded controller with phpunit?

I am using embedded controllers to generate dynamic content in side templates(eg: a menu)


Usually, I implement functionnal tests to assert controllers. So far, functionnal tests are passing and phpunit considers my embedded controllers code-covered


I am wondering how to test the embedded controller with different inputs and evaluate the outputs... Is that Unit Testing right ?


I know Unit Testing controller is a bad practice, but how can I function test an embedded controller when there is no Request Object ? The route/url is something that the Twig render() function takes care of.


{{ render(controller('AppSuperBundle:Default:generateMenu', {'params': ... } )) }}


An example to illustrate:



class DefaultController extends Controller
{
public function testAction()
{
return $this->render('AppSuperBundle::index.html.twig');
}

public function generateMenuAction($route, Array $RouteParams)
{
$repo = $this->getDoctrine()->getRepository(...
//some process to generate params of menu items (eg:locale, url, name...)

return $this->render('AppSuperBundle::menu.html.twig', array('menuItems' => $menuItemsWithParams));
}
}


The template index.html.twig



<html>
<body>
{% block menu %}
{{ render(controller('AppSuperBundle:Default:generateMenu', {'route': app.request.attributes.get('_route'), 'RouteParams': app.request.attributes.get('_route_params')} )) }}
{% endblock %}
{% block content %}
...
{% endblock %}
</body>
</html>


What are your thoughts on this ?


Aucun commentaire:

Enregistrer un commentaire