15/03/2018 - PHPUNIT, SYMFONY
This example shows us how we can test Symfony Request headers with PHPUnit. All it does is, injects header parameter into Request and calls $request->headers->get('token')
.
declare(strict_types=1);
namespace AppBundle\Security\TokenAuthenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
class TokenAuthenticator
{
public function createToken(Request $request, $providerKey)
{
$token = $request->headers->get('token');
if ($token === 'MY-TOKEN') {
$email = 'MY@EMAIL.COM';
} else {
....
}
return new PreAuthenticatedToken('anon.', $email, $providerKey);
}
}
declare(strict_types=1);
namespace Tests\AppBundle\Security;
use AppBundle\Security\TokenAuthenticator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
class TokenAuthenticatorTest extends TestCase
{
/**
* @test
*/
public function create_token_returns_token_for_known_token_user()
{
$providerKey = 'PROVIDER-KEY';
$knownToken = 'MY-TOKEN';
$email = 'MY@EMAIL.COM';
$request = new Request([], [], [], [], [], ['HTTP_token' => $knownToken]); # Header key must be prefixed with "HTTP_"
$this->assertSame($knownToken, $request->headers->get('token'));
$token = new PreAuthenticatedToken('anon.', $email, $providerKey);
$result = (new TokenAuthenticator())->createToken($request, $providerKey);
$this->assertEquals($token, $result);
}
}
PHPUnit 6.3.1 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 74 ms, Memory: 6.00MB
OK (1 test, 2 assertions)