2012-02-07 14 views

答えて

0

私はプロジェクトのひとつのためにそれを実装する方法である(ないFOSUserBundleで、おそらくあなたはそれが役に立つ見つけることができます)

private function createAuthorizedClient($role) 
{ 
    $userProvider = new YourUserProvider(...); 
    $user = $userProvider->createUserMethod(...); 

    $client = $this->createClient(); //Normal WebTestCase client 
    $client->getCookieJar()->set(new Cookie(session_name(), true)); 
    $session = self::$kernel->getContainer()->get('session'); 
    $token = new UsernamePasswordToken($user, 'password', 'main', array($role)); 
    $client->getContainer()->get('security.context')->setToken($token); 
    $session->set('_security_main', serialize($token)); 

    return $client; 
} 

は、ユーザーオブジェクトの期待される結果を模擬することを忘れないでください。

5

実際には、実際のユーザーのように認証を行う必要があります。その場合、あなたは私は手遅れになる知っている..しかし、場合には、誰かがこれを必要とする平野パスワードを知っていると、ログインフォーム

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; 
class XXX extends WebTestCase { 
    public function testUserLogin() { 

    $client = static::createClient(); 
    $client->request('GET', '/login'); 

    $form = $crawler->selectButton('_submit')->form(array(
    '_username' => 'user', 
    '_password' => 'pa$$word', 
    )); 

    $client->submit($form); 
    $crawler = $client->followRedirect(); // "/" page 

    // if credentials were correct, you should be logged in and ready to test your app 
    } 
} 
+0

symfony 3.4で動作しています(ありがとうございます) – HTDutchy

2

を入力する必要があり、私はこのように私のユニットテストでユーザーをloggに管理しました:

<?php 

namespace Tests\Menu; 

use Tests\ContainerAwareUnitTestCase; 
use UserBundle\Entity\User; 
use FOS\UserBundle\Security\UserProvider; 
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; 
use Symfony\Component\Security\Core\SecurityContext; 
use Symfony\Component\HttpFoundation\Request; 
use Menu\MenuBuilder; 

class MenuBuilderTest extends ContainerAwareUnitTestCase 
{ 
    public function provider() 
    { 
     return array(array('/')); 

    } 

    /** 
    * @dataProvider provider 
    */ 
    public function testNoAuth($uri) 
    { 
     /* @var $securityContext SecurityContext */ 
     $securityContext = $this->get('security.context'); 
     $userProvider = $this->get('fos_user.user_provider.username'); 
     $user = $userProvider->loadUserByUsername('alex'); 
     $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER')); 
     $securityContext->setToken($token); 

     /* @var $menuBuilder MenuBuilder */ 
     $menuBuilder = $this->get('event_flow_analyser.menu_builder'); 

     $this->assertNotNull($menuBuilder); 

     $request = new Request(); 
     $request->attributes->set('projectName', 'ucs'); 

     $menu = $menuBuilder->createMainMenu($request); 

     $this->assertNotNull($menu); 

     $this->assertNotNull($menu->getChild('Home')); 
     $this->assertNotNull($menu->getChild('Profile')); 

     $this->assertEquals(null, $menu->getChild('Projects')); 
    } 

}  

<?php 
namespace Tests; 

class ContainerAwareUnitTestCase extends \PHPUnit_Framework_TestCase 
{ 
    protected static $kernel; 
    protected static $container; 

    public static function setUpBeforeClass() 
    { 
     self::$kernel = new \AppKernel('dev', true); 
     self::$kernel->boot(); 

     self::$container = self::$kernel->getContainer(); 
    } 

    public function get($serviceId) 
    { 
     return self::$kernel->getContainer()->get($serviceId); 
    } 
} 

2-その後、次のようにテストを宣言:

1-まず、あなたがサービスにアクセスできるようになりますクラスを定義します。

このMenuBuilderの作成をテストするための完全なexemple、少し範囲外ものの、そのエキスがあなたの必要性に答える必要があります。

 $securityContext = $this->get('security.context'); 
     $userProvider = $this->get('fos_user.user_provider.username'); 
     $user = $userProvider->loadUserByUsername('alex'); 
     $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER')); 
     $securityContext->setToken($token); 
3

この質問への既存の回答が参考にされているが、それらのどれも私の問題を解決しません直接。私はSymfony 2.3を使用しています。

<?php 

namespace CDE\TestBundle\Base; 

use FOS\UserBundle\Model\User; 
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; 
use Symfony\Component\BrowserKit\Cookie; 
use Symfony\Component\BrowserKit\CookieJar; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Session\Session; 
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage; 
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; 

class BaseUserTest extends WebTestCase { 

    protected $client; 
    protected $container; 
    protected $storage; 
    protected $session; 
    protected $user; 
    protected $cookieJar; 
    protected $cookie; 
    protected $token; 

    public function __construct() { 
     $this->client = static::createClient(); 
     $this->container = $this->client->getContainer(); 
     $this->storage = new MockFileSessionStorage(__dir__.'/../../../../app/cache/test/sessions'); 
     $this->session = new Session($this->storage); 

    } 

    public function getUserManager() { 
     return $this->container->get('cde_user.manager.user'); 

    } 

    public function getSecurityManager() { 
     return $this->container->get('fos_user.security.login_manager'); 

    } 

    public function getUser($role = null) { 
     if (!isset($this->user)) { 
      $user = $this->getUserManager()->loadByUsername('user'); 

      if (isset($user)) { 
       $this->user = $user; 
      } else { 
       $this->user = $this->getUserManager()->create(); 

       $this->user->setEnabled(true); 
       $this->user->setUsername('user'); 
       $this->user->setEmail('[email protected]'); 
       $this->user->setPlainPassword('user'); 
       $this->getUserManager()->updatePassword($this->user); 
       if (isset($role)) { 
        $this->user->addRole($role); 
       } 
       $this->getUserManager()->add($this->user); 
      } 

     } 

     return $this->user; 
    } 

    public function logIn(User $user, Response $response) { 
     $this->session->start(); 

     $this->cookie = new Cookie('MOCKSESSID', $this->storage->getId()); 
     $this->cookieJar = new CookieJar(); 
     $this->cookieJar->set($this->cookie); 
     $this->token = new UsernamePasswordToken($user, 'user', 'main', $user->getRoles()); 
     $this->session->set('_security_main', serialize($this->token)); 


     $this->getSecurityManager()->loginUser(
      $this->container->getParameter('fos_user.firewall_name'), 
      $user, 
      $response 
     ); 

     $this->session->save(); 
    } 

    public function removeUser(User $user) { 

    } 
} 

RestControllerTest.phpコードを容易にユーザにログインするように拡張することができるベーステストクラス(BaseUserTest.php)を含む

<?php 

namespace CDE\ContentBundle\Tests\Controller; 

use CDE\TestBundle\Base\BaseUserTest; 
use Symfony\Component\HttpFoundation\Response; 

class RestControllerTest extends BaseUserTest 
{ 
    protected $comment; 

    public function __construct() { 
     parent::__construct(); 
     $this->logIn($this->getUser('ROLE_ADMIN'), new Response()); 

    } 

    public function getGalleryManager() { 
     return $this->container->get('cde_content.manager.gallery'); 
    } 

    public function getAWSManager() { 
     return $this->container->get('cde_utility.manager.aws'); 
    } 

    public function createGallery() 
    { 
     //  Copy test.jpeg into the web folder 
     $filename = 'gallery/user-test.jpg'; 
     copy(__DIR__.'/../Mock/test.jpeg', __DIR__.'/../../../../../web/'.$filename); 
     $this->getAWSManager()->copyGalleryFile($filename); 


     $gallery = $this->getGalleryManager()->create(); 
     $gallery->setUser($this->getUser()); 
     $gallery->setFilename($filename); 
     $gallery->setTitle('test gallery'); 
     $gallery->setDescription('test gallery description'); 
     $gallery->setMarked(false); 
     $this->getGalleryManager()->add($gallery); 
     $this->assertEquals($gallery->getMarked(), false); 
    } 

    public function createComment() 
    { 
     $galleries = $this->getGalleryManager()->findByUser($this->getUser()); 
     $gallery = $galleries[0]; 

     $client = static::createClient(); 
     $client->getCookieJar()->set($this->cookie); 
//  $client = static::createClient(array(), new History(), $cookieJar); 

     $crawler = $client->request('POST', 'api/createComment/'.$gallery->getId(), array(
      'comment' => 'testing testing 123', 
      'marked' => 'false' 
     )); 

     $response = $client->getResponse(); 
     $this->comment = json_decode($response->getContent()); 
     $this->assertEquals($this->comment->comment, 'testing testing 123'); 
     $this->assertFalse($this->comment->marked); 
     $this->assertEquals($response->getStatusCode(), 200); 
    } 

    public function getComment() 
    { 
     $client = static::createClient(); 

     $crawler = $client->request('GET', 'api/getComment/'.$this->comment->id); 

     $response = $client->getResponse(); 
     $comment = json_decode($response->getContent()); 
     $this->assertEquals($comment->comment, 'testing testing 123'); 
     $this->assertFalse($comment->marked); 
     $this->assertEquals($response->getStatusCode(), 200); 

    } 

    public function updateComment() 
    { 
     $client = static::createClient(); 

     $crawler = $client->request('GET', 'api/updateComment'); 
    } 

    public function deleteComment() 
    { 
     $client = static::createClient(); 

     $crawler = $client->request('DELETE', 'api/deleteComment'); 
    } 

    public function getComments() 
    { 
     $client = static::createClient(); 

     $crawler = $client->request('GET', 'api/getComments'); 
    } 

    public function getGalleries() 
    { 
     $client = static::createClient(); 

     $crawler = $client->request('GET', 'api/getGalleries'); 
    } 

    public function removeGallery() { 
     $galleries = $this->getGalleryManager()->findByUser($this->getUser()); 
     foreach ($galleries as $gallery) { 
      $this->getGalleryManager()->remove($gallery); 
     } 

    } 

    public function testComments() { 
     $this->createGallery(); 
     $this->createComment(); 
     $this->getComment(); 
     $this->updateComment(); 
     $this->deleteComment(); 
     $this->getComments(); 
     $this->getGalleries(); 
     $this->removeGallery(); 
    } 

} 

はここに私の解決策です。

サンプルテスト(RestControllerTest.php)で基本クラスを使用する方法の例も示しました。 RestControllerTest.phpにこのコードブロックに注目してください:

$client = static::createClient(); 
$client->getCookieJar()->set($this->cookie); 

BaseUserTestの背後にある考え方は、それは、それ自身のセッションを作成し、ユーザーとのセッションを移入し、その後MockFileSessionStorageを使用してファイルシステムにセッションを保存することができるということです。

テスト自体は、クッキーをクライアントに設定する必要があります。

+0

こんにちは、私はあなたの解決策が好きです。これに関するsecurity.yml設定を貼り付けてください。 – r4ccoon

0

私はあなたのソリューションにコメントできないので、私は新しい回答を作成する必要があります。実際には、他のソリューションは、特定のシナリオをテストするために機能テストを使用するという点で正しいです。ユニットテストを使用して機能テストに属するシナリオをテストしています。そのため、ユーザーログインをハッキングする必要がありました。他の解決策を考えて、正しいメニュー項目のDOMオブジェクトをチェックして、機能テストを行ってください。

関連する問題