2017-06-24 25 views
1

我想测试我在Symfony 3.3.2中创建的应用程序。
我使用FOSUserBundle作为我的用户系统。在Symfony 3.3中用假用户进行功能测试

我在安装程序中创建一个新的客户端

public function setUp() { 
    $this->client = static::createClient(); 
} 

我写了一个简单的功能,应该由FOS服务创建虚假用户

private function logInAdmin() { 
    $fosLoginManager = $this->client->getContainer()->get('fos_user.security.login_manager'); 

    $user = new User(); 
    $user->setEnabled(true); 
    $user->addRole('ROLE_ADMIN'); 

    $fosLoginManager->logInUser('main', $user); 
} 

其实这种情况正在发生,但只有当我手动测试此代码在控制器中。在这种情况下,我以用户的身份登录,我刚刚在代码中创建。我有我的角色等。但是,当PHPUnit运行此代码时,用户变成null

为什么会发生这种情况?如何正确地做到这一点?

回答

1
<?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 

运行functionnals测试之前,我与建设的模式和一些灯具分贝。

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 

在灯具内部我创建一个管理员用户。

我只是做了这个,现在测试通过了。

+0

我做了,但它不适合我。这就是为什么我问 – Night

+0

我刚刚编辑我的答案,希望这会帮助你 – jeremy

+0

它现在的作品,谢谢!我现在头脑中混乱很多。我确信我尝试了完全相同的代码,但它不工作,所以我开始尝试使用FOS; - ; – Night

相关问题