gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:05:33 25 4
gpt4 key购买 nike

我正在为几种返回 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com