如何测试预期的标头?

时间:2012-02-03 10:37:30

标签: phpunit

我的单元测试失败,因为标头已经发送。但是,此方案中的标题是预期的。

如何告诉PHPUnit期望500头?

我看过this question,但没有帮助。

该方法包含在输出缓冲区中。

ob_start();
$foo->methodWhichSendsHeader();
ob_clean();

3 个答案:

答案 0 :(得分:20)

如果安装了xdebug,则可以使用xdebug_get_headers()来获取标头。然后你可以根据需要测试它们。

$headers=xdebug_get_headers();

获取一个看起来像......

的数组
array(
    0 => "Content-type: text/html",
    1 => ...
)

因此,您需要解析每个标题行以将标题名称与值

分开

答案 1 :(得分:2)

如果你不能在你的系统上使用xdebug_get_headers,另一种方法是模拟头函数。

我现在正在使用以下内容,效果很好。让我们说你有这个代码......

<?php
header('Content-type: text/plain; charset=UTF-8');
...

我用一个可以测试的标题函数替换header ......

<?php
Testable::header('Content-type: text/plain; charset=UTF-8');
...

Testable类实现如下。请注意,函数只需要添加Testable::。否则它们的工作方式与通常的功能相同。

class Testable {
   private static $headers=array();

   static function header($header) {
      if (defined('UNIT_TESTING')) {
         self::$headers[]=$header;
      } else {
         header($header);
      }
   }

   public static function reset() {
      self::$headers=array();
   }

   public static function headers_list() {
      if (defined('UNIT_TESTING')) {
          return self::$headers;
      } else {
          return headers_list();
      }
   }
}

现在您需要做的就是在测试中定义UNIT_TESTING,但不要在生产中定义。然后,当您来测试标题时,只需致电Testable::headers_list()

您当然应该为setcookie,headers_sent和任何其他发布HTTP标头的函数添加方法。

答案 2 :(得分:0)

另一种可能的方法是为要测试的名称空间覆盖header php函数。 https://www.codepunker.com/blog/overwrite-built-in-php-functions-using-namespaces

namespace My\Application\Namespace;
use My\Test\Application\Namespace;    

//this overrides the header function for that namespace
//it works only if the function is called without the backslash
function header($string){
    HeaderCollector::$headers[] = $string;
}

namespace My\Test\Application\Namespace

/**
 * Class HeaderCollector
 * Using this in combination with function header override
 * for the namespace My\Application\Namespace
 * we can make assertions on headers sent
 */
class HeaderCollector {

    public static $headers = [];

    //call this in your test class setUp so headers array is clean before each test
    public static function clean() {
        self::$headers = [];
    }
}

然后在您的测试课中

namespace My\Test\Application\Namespace
use PHPUnit\Framework\TestCase;


class MyTest extends TestCase {

    protected function setUp() {
        parent::setUp();
        //clean for each test
        HeaderCollector::clean();
    }

    public function testHeaders() {
        //call the code that send headers
        ...

        self::assertEquals(
            ["Content-Type: text/html; charset=UTF-8", "Another-Header..."],
            HeaderCollector::$headers
        );
    }
}

您可以保持代码干净,不需要xdebug