簡體   English   中英

如何在進行單元測試時覆蓋php://輸入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM