<?php
namespace AdminBundle\Security;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class LoginTest extends WebTestCase
{
/**
* @var Client
*/
private $client = null;
protected function setUp()
{
$this->client = static::createClient();
}
private function logIn()
{
$session = $this->client->getContainer()->get('session');
// the firewall context defaults to the firewall name
$firewallContext = 'main';
$token = new UsernamePasswordToken('admin', null, $firewallContext, array('ROLE_ADMIN'));
$session->set('_security_'.$firewallContext, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}
public function testLoginToBackOffice()
{
$this->logIn();
$crawler = $this->client->request('GET', '/admin');
$response = $this->client->getResponse();
$this->assertSame(Response::HTTP_OK, $response->getStatusCode());
//200 means i am logged in else should be a redirection to the login path
}
}
我将 sqlite3 用作我的测试数据库层,这是我放入 config_test.yml 的内容
doctrine:
dbal:
driver: pdo_sqlite
path: "%kernel.cache_dir%/db"
charset: UTF8
在运行功能测试之前,我用架构和一些固定装置构建了一个数据库。
php bin/console doctrine:database:drop --force --env=test
php bin/console doctrine:database:create --env=test
php bin/console doctrine:schema:create --env=test
php bin/console doctrine:fixtures:load --env=test -n
在夹具内部,我创建了一个管理员用户。
我刚刚这样做了,现在测试通过了。