[英]how do I override php://input when doing unit tests
我正在尝试使用Zend和PHPUnit为控制器编写单元测试
在代码中我从php:// input获取数据
$req = new Zend_Controller_Request_Http();
$data = $req->getRawBody();
当我测试真实的应用程序时,我的代码工作正常,但除非我可以提供数据作为原始http帖子,否则$ data将始终为空。 getRawBody()方法基本上调用file_get_contents('php:// input'),但是如何覆盖它以便将测试数据提供给我的应用程序。
我遇到了同样的问题,我修复它的方法是将'php://input'
字符串作为可在运行时设置的变量。 我知道这并不直接适用于这个问题,因为它需要修改Zend Framework。 但同样的,它可能对某人有所帮助。
例如:
<?php
class Foo {
public function read() {
return file_get_contents('php://input');
}
}
会成为
<?php
class Foo {
public $_fileIn = 'php://input';
public function read() {
return file_get_contents($this->_fileIn);
}
}
然后在我的单元测试中我可以做到:
<?php
$obj = new Foo();
$obj->_fileIn = 'my_input_data.dat';
assertTrue('foo=bar', $obj->read());
您可以尝试在单元测试中模拟对象。 像这样的东西:
$req = $this->getMock('Zend_Controller_Request_Http', array('getRawBody'));
$req->method('getRawBody')
->will($this->returnValue('raw_post_data_to_return'));
假设$req->getRawBody()
就像你说的那样,与file_get_contents('php://input')
......
$test = true; /* Set to TRUE when using Unit Tests */
$req = new Zend_Controller_Request_Http();
if( $test )
$data = file_get_contents( 'testfile.txt' );
else
$data = $req->getRawBody();
不是一个完美的解决方案,但类似于我过去在设计脚本来处理管道电子邮件时所使用的非常成功。
Zend_Controller_Request_HttpTestCase包含用于设置和获取各种http请求/响应的方法。
例如: $req = new Zend_Controller_Request_HttpTestCase; $req->setCookie('cookie', 'TRUE'); $test = $this->controller->cookieAction($req); $this->assertSame($test, TRUE);
$req = new Zend_Controller_Request_HttpTestCase; $req->setCookie('cookie', 'TRUE'); $test = $this->controller->cookieAction($req); $this->assertSame($test, TRUE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.