在PHPUnit中测试表单输入 [英] Testing form inputs in PHPUnit

查看:64
本文介绍了在PHPUnit中测试表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试PHPUnit中的$_GET$_POST输入的最佳方法是什么?

What's the best way to test $_GET and $_POST inputs in PHPUnit?

我有一个可以清除输入内容的类,并希望在处理虚假数据时检查其是否正常工作.是否有一种简单的方法可以在PHPUnit中设置表单变量,还是我应该将验证传递给被馈给表单变量的间接类/函数,以便间接地对其进行测试?

I have a class that sanitises input and want to check that it works correctly when processing bogus data. Is there an easy way to set up the form variables in PHPUnit or should I just pass off the validation to a secondary class/functions that are fed the form variables so test them indirectly?

推荐答案

看看依赖项的想法注射.简而言之,您应该向代码提供所需的内容,而不是获取所需的数据...这是一个示例:

Take a look at the idea of Dependency injection. In a nutshell you should feed your code what it needs as opposed to it getting the data it needs... Here's an example:

没有依赖注入的示例

function sanitize1() {
  foreach($_POST as $k => $v) {
    // code to sanitize $v
  }
}

sanitize1();

具有依赖项注入的示例

function sanitize2(array &$formData) {
  foreach($formData as $k => $v) {
    // code to sanitize $v
  }
}

sanitize2($_POST);

看到区别了吗?在您的PHPUnit测试中,您可以通过sanitize2()一个您选择的关联数组.您已经注入了依赖项.而sanitize1()$_POST耦合. $_POST$_GET都是assoc数组,因此在生产代码中可以将$_GET$_POST传递给函数,但是在单元测试中,您将对一些预期的数据进行硬编码.

See the difference? In your PHPUnit test you can pass sanitize2() an associative array of your choice; you've injected the dependency. Whereas sanitize1() is coupled with $_POST. $_POST and $_GET are assoc arrays anyways so in your production code you can pass $_GET or $_POST to your function but in your unit tests you'd hard code some expected data.

单元测试示例:

function testSanitize() {
  $fakeFormData = array ('bio' => 'hi i\'m arin', 'location' => 'San Francisco');
  sanitize($fakeFormData);
  // assert something
}

这篇关于在PHPUnit中测试表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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