我正在尝试使用Zend和PHPUnit为控制器编写单元测试
在代码中,我从php://input获取数据
$req = new Zend_Controller_Request_Http();
$data = $req->getRawBody();
当我测试真实的应用程序时,我的代码运行得很好,但是除非我能以原始http post的形式提供数据,否则$data总是空白的。getRawBody()方法基本上调用file_get_contents('php://input'),但是我如何重写它才能将测试数据提供给我的应用程序。
发布于 2010-07-11 13:43:18
假设$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();
这不是一个完美的解决方案,但类似于我过去在设计脚本来处理管道电子邮件时所使用的脚本,并取得了巨大的成功。
发布于 2011-03-24 21:46:41
我也遇到了同样的问题,我解决这个问题的方法是将'php://input'
字符串作为一个可在运行时设置的变量。我知道这并不直接适用于这个问题,因为它需要修改Zend框架。但尽管如此,它也可能对某些人有所帮助。
例如:
<?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());
发布于 2010-07-12 01:59:02
您可以尝试在单元测试中模拟对象。如下所示:
$req = $this->getMock('Zend_Controller_Request_Http', array('getRawBody'));
$req->method('getRawBody')
->will($this->returnValue('raw_post_data_to_return'));
https://stackoverflow.com/questions/3221542
复制相似问题