php - 在 PHPUnit 中验证 HTTP 响应代码

标签 php unit-testing phpunit

我正在为几种返回 HTTP 响应代码的方法编写单元测试。我找不到断言 HTTP 响应代码的方法。也许我遗漏了一些明显的东西,或者我对 PHPUnit 有误解。

我正在使用 PHPUnit 4.5 稳定版。

类消息的相关部分:

public function validate() {
  // Decode JSON to array.
  if (!$json = json_decode($this->read(), TRUE)) {      
    return http_response_code(415);
  }
  return $json;
}

// Abstracted file_get_contents a bit to facilitate unit testing.
public $_file_input = 'php://input';

public function read() {
  return file_get_contents($this->_file_input);
}

单元测试:
// Load invalid JSON file and verify that validate() fails.
public function testValidateWhenInvalid() {
  $stub1 = $this->getMockForAbstractClass('Message');
  $path =  __DIR__ . '/testDataMalformed.json';
  $stub1->_file_input = $path;
  $result = $stub1->validate();
  // At this point, we have decoded the JSON file inside validate() and have expected it to fail.
  // Validate that the return value from HTTP 415.
  $this->assertEquals('415', $result);
}

PHPUnit 返回:
1) MessageTest::testValidateWhenInvalid
Failed asserting that 'true' matches expected '415'.

我不确定为什么 $result 会返回 'true' 。 . .特别是作为字符串值。也不确定我的“预期”论点应该是什么。

最佳答案

According to the docs您可以调用http_response_code()没有参数的方法来接收当前的响应代码。

<?php

http_response_code(401);
echo http_response_code(); //Output: 401

?>

因此,您的测试应如下所示:
public function testValidateWhenInvalid() {
    $stub1 = $this->getMockForAbstractClass('Message');
    $path =  __DIR__ . '/testDataMalformed.json';
    $stub1->_file_input = $path;
    $result = $stub1->validate();
    // At this point, we have decoded the JSON file inside validate() and have expected it to fail.
    // Validate that the return value from HTTP 415.
    $this->assertEquals(415, http_response_code()); //Note you will get an int for the return value, not a string
}

关于php - 在 PHPUnit 中验证 HTTP 响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28681335/

相关文章:

c++ - 测试抛出失败的函数

phpunit - PhpStorm PHPUnit 测试报告程序错误

PHPUnit:为自定义断言编写测试

php file_get_contents() 在加载图像时卡住

c# - 生成基于对象的当前值创建构造函数的代码的方法?

php - 在隐藏的 div 中显示 PHP 中的 MySQL 数据

ruby-on-rails - BDD with Cucumber 和 rspec - 什么时候这是多余的?

php - Selenium 不显示失败的数字行

php - 如何在 Php mySql 中按字母顺序显示表数据?

php - MySQL查询具有多个条件但结果有限