验证PHPUnit中的HTTP响应代码

验证PHPUnit中的HTTP响应代码,php,unit-testing,phpunit,Php,Unit Testing,Phpunit,我正在为几种返回HTTP响应代码的方法编写单元测试。我找不到断言HTTP响应代码的方法。也许我遗漏了一些明显的东西,或者我对PHPUnit有些误解 我使用的是phpunit4.5稳定版 课程信息的相关部分: public function validate() { // Decode JSON to array. if (!$json = json_decode($this->read(), TRUE)) { return http_response_code(

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

我使用的是phpunit4.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”。尤其是作为字符串值。也不确定我的“预期”参数应该是什么。

您可以调用不带参数的
http\u response\u code()
方法来接收当前响应代码

<?php

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

?>

如果方法返回代码,那么
assertEquals()
就不能完成任务了吗?你能提供类和测试吗?@cracketastic我不确定在assertEquals()中使用什么作为预期参数,因为我从http_响应_code()返回的返回值是字符串形式的“true:-|@PiotrOlaszewski用代码更新。太好了!我从测试中删除了$result,因为它不是必需的。好主意!没问题!很乐意帮忙。
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
}