问题描述
我开始使用PHPUnit与Kohana的工作。我的应用程序有许多控制器,只需从某种形式的数据,验证和插入/更新/删除到/ - /从数据库。我应该如何写一个测试用例。
I'm starting work with PHPUnit with Kohana. My application have many controllers which simply takes data from some form, validates and inserts/updates/deletes into/-/from database. How should I write a test cases for that.
我知道如果我想测试一个函数,我写数据提供者函数,只是比较返回的值与期望的。但我的输入数据(来自表单的数据)在 $ _ POST
变量中传递。我应该如何测试这个?之后,我应该检查插入的数据是否真的在数据库中?请给我一些指导这种类型的测试或链接到一些例子/教程。谢谢。
I know that if I want to test a function I write data provider function and just compare returned value with the expected one. But my input data (data from forms) is being passed in $_POST
variable. How should I test this? And after that, should I check if inserted data is really in database? Please give my some guidlines for that type of tests or links to some examples/tutorials. Thanks.
推荐答案
首先,如果您从接收POSTed数据到检查数据库中的值,这不是单元测试:你不是测试一个组件隔离其他组件,但你正在测试这些组件的集成在一起。
First of all, if you are testing all the way from receiving the POSTed data to checking values in the database, this is not unit-test anymore : you are not testing one component in isolation of the others, but you are testing the integration of those components together.
这使事情更难要测试:
- 您必须以更难的方式提供数据:不仅仅是作为方法的参数,而是作为整个应用程序的参数(这意味着伪造POST数据,例如这里)
- 您有更多的东西要验证:不仅仅是一个方法的返回值,异常
- 您有几个不同的,也许不相关的事情,可能会导致失败(一些PHP代码中的问题,数据库中的问题,数据库服务器不可用,...) ,这将使故障更难跟踪找到原因。
- you have to provide data in harder ways : not just as parameters to a method, but as parameters to your whole application (which means forging POST data, here, for instance)
- you have more things to verify : not just the return value of a method, or if it threw an exception
- you have several different and maybe unrelated things that can cause a failure (problem in some PHP code, problem in the database, database server not being available, ...), which will make failures harder to track down to find their cause.
请注意,我没有说那种集成测试没有用,btw; - )
Note that I didn't say that kind of "integration" tests is not useful, btw ;-)
仍然,锻造 $ _ POST
数组很简单:它不是只读的,你可以存储任何你想要的。
Still, forging the $_POST
array is quite simple : it is not read-only, and you can store whatever you want in it.
在你的测试用例开始时,没有什么能阻止你注入你所需要的任何数据。
So, at the begining of your test-case, nothing prevents you from injecting any data you need in it.
这篇关于PHPUnit - 使用$ _POST变量测试MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!