Last active
June 14, 2021 06:50
-
-
Save vielhuber/17799c5b324d2653765aa0c868225913 to your computer and use it in GitHub Desktop.
properly test header redirect in phpunit #php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// src/App.php | |
namespace Example; | |
class App | |
{ | |
public function redirect($url) | |
{ | |
header('Location: ' . $url, true, 302); | |
die(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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