Bu örnek bize PHPUnit ile Symfony Request header testinin nasıl yapılacağını gösteriyor. Tüm yapılan şey, header parametresini Request objesine enjekte etmek ve $request->headers->get('token') kodunu çağırmak.


Class


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);
}
}

Test


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);
}
}

Sonuç


PHPUnit 6.3.1 by Sebastian Bergmann and contributors.

. 1 / 1 (100%)

Time: 74 ms, Memory: 6.00MB

OK (1 test, 2 assertions)