I have a unit test that fails because headers are already sent. However, the header in this scenario is expected.
How do I tell PHPUnit to expect a 500 header?
I've read this question but it didn't help.
The method is wrapped inside an output buffer.
ob_start();
$foo->methodWhichSendsHeader();
ob_clean();
If you want to check the HTTP headers or response headers for a particular web page, you can perform the following steps. Open the HTTP Header Checker. Enter any valid domain or IP address to check the response headers, and click on the "Check HTTP Headers" button.
The HTTP Headers test requests the entered URL, retrieves the HTTP response headers, verifies the HTTP status codes and displays the received response headers (redirects included).
HTTP Headers are an important part of the API request and response as they represent the meta-data associated with the API request and response. Headers carry information for: Request and Response Body. Request Authorization. Response Caching.
So here's how a simple test to verify that the common response headers are present: pm. test("Verify response headers are present ", () => { pm. response.to.have.
Another possible approach is to override the header
php function for the namespace you are testing.
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 = [];
}
}
Then in your test class
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
);
}
}
You can keep your code clean and you don't need xdebug
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With