Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active June 14, 2021 06:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vielhuber/17799c5b324d2653765aa0c868225913 to your computer and use it in GitHub Desktop.
Save vielhuber/17799c5b324d2653765aa0c868225913 to your computer and use it in GitHub Desktop.
properly test header redirect in phpunit #php
<?php
// src/App.php
namespace Example;
class App
{
public function redirect($url)
{
header('Location: ' . $url, true, 302);
die();
}
}
<?php
// tests/Test.php
namespace Example;
class Test extends \PHPUnit\Framework\TestCase
{
protected $app;
protected function setUp(): void
{
$this->app = $this->getMockBuilder(App::class)
->setConstructorArgs([])
->onlyMethods(['redirect'])
->getMock();
$this->app
->expects($this->any())
->method('redirect')
->will(
$this->returnCallback(function ($url) {
throw new \Exception($url);
})
);
}
public function testRedirect()
{
try {
$this->app->redirect('https://test.de');
}
catch(\Exception $e) {
$this->assertEquals($e->getMessage(), 'https://test.de');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment