作者:dengru42 | 来源:互联网 | 2023-05-20 18:06
我正在为返回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'。。。特别是作为字符串值。同样不确定我的“预期”论点应该是什么。
1> Crackertasti..:
根据文档,您可以http_response_code()
不带任何参数的方法调用以接收当前响应代码。
因此,您的测试应如下所示:
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
}