How can I unit test a Symfony2 controller?

前端 未结 4 961
暖寄归人
暖寄归人 2021-01-31 16:42

I want to use Test Driven Development as much as possible — it\'s a great way of working.

I am troubled by the fact that Symfony2 controllers create and return a new

4条回答
  •  佛祖请我去吃肉
    2021-01-31 17:27

    Normally, your controller plugs together different objects and connects them in the correct order. Maybe he calls a repository, reads some objects and returns them through the render method. Maybe he calls some other Handlers/Managers who do stuff.

    This means that a controller is a high level component. More often than not this indicates that functional tests are in order instead of unit tests. You should not aim to get 100% code coverage with your unit tests. Maybe you can think of it that way: If you unit test everything the controller calls (model, validation, form, repository), what could go wrong? Most of the time it's something you only observe when using all the real classes involved when in production.

    I want also like to point out that TDD does not mean that everything has to be unit-tested. It's ok to have some functional tests for the high-level code. As said, if you test the low-level components with unit-tests you should only test how they are working together which you cannot test with mocks because you tell the mocks what the return value is.

    If your controller does more than plugging parts of the system together you should think about refactoring the stuff into more low-level classes you can test with unit-tests.

    So my suggestion would be to use functional tests to test your controllers and use unit-tests to test your models and your business logic stuff.

    If you struggle with functional tests, you can read the following:

    • http://symfony.com/doc/current/book/testing.html#functional-tests
    • http://blog.sznapka.pl/fully-isolated-tests-in-symfony2/

提交回复
热议问题