如何对 Symfony2 控制器进行单元测试? [英] How can I unit test a Symfony2 controller?

查看:27
本文介绍了如何对 Symfony2 控制器进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尽可能多地使用测试驱动开发——这是一种很棒的工作方式.

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

Symfony2 控制器创建并返回一个新的 Response 对象这一事实让我感到困扰.

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

我希望能够单独对控制器进行单元测试.

I want to be able to unit test a controller in isolation.

你是怎么做到的?

是将控制器创建为普通旧 PHP 对象,将其注册为服务并使用依赖注入来传递新的 Response 对象(或 Response工厂)进去?

Is the answer to create a controller as a Plain Old PHP Object, register it as a service and use Dependency Injection to pass a new Response object (or a Response factory) into it?

推荐答案

通常,您的控制器将不同的对象连接在一起并以正确的顺序连接它们.也许他调用一个存储库,读取一些对象并通过render 方法返回它们.也许他会打电话给其他一些做事的处理人员/经理.

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.

这意味着控制器是一个高级组件.这通常表明功能测试是有序的,而不是单元测试.您不应该旨在通过单元测试获得 100% 的代码覆盖率.也许您可以这样想:如果您对控制器调用的所有内容(模型、验证、表单、存储库)进行单元测试,会出现什么问题?大多数情况下,只有在使用生产中涉及的所有真实类时才会观察到这种情况.

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.

我还想指出,TDD 并不意味着一切都必须经过单元测试.可以对高级代码进行一些功能测试.如前所述,如果您使用单元测试来测试低级组件,您应该只测试它们如何协同工作,而不能使用模拟进行测试,因为您告诉模拟返回值是什么.

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:

这篇关于如何对 Symfony2 控制器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆