本文介绍了PHPUnit - 使用 $_POST 变量测试 MVC 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 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.

这让测试变得更加困难:

It makes things harder to test :

  • 您必须以更难的方式提供数据:不仅仅是作为方法的参数,而是作为整个应用程序的参数(例如,这里意味着伪造 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.


请注意,我并没有说那种集成"测试没有用,顺便说一句;-)


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 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:03