3

これからテストクラスを継承して、Symfony2コントローラーの機能テストを行っています。

class InsecureWebTestCase extends WebTestCase {

    protected $client = null;

    public function setUp() {
        $this->client = static::createClient();
        $session = $this->client->getContainer()->get('session');
        $firewall = 'default';
        $token = new UsernamePasswordToken('norbert.scrunge@gmail.com', null, $firewall, array('ROLE_USER', 'ROLE_ADMIN'));
        // $this->client->getContainer()->get('security.context')->setToken($token);
        $session->set("_security_$firewall", serialize($token));
        $session->save();
        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }

}

コントローラーをアプリの一部として使用する と、Doctrine の「ユーザー」エンティティのインスタンスに$this->container->get('security.token_storage')->getToken()->getUser()なります。$this->getUser()

ただし、機能テストを実行する場合: $this->container->get('security.token_storage')->getToken()->getUser()はユーザー名を含む文字列で、$this->getUser()NULL.

アプリと機能テストで動作の一貫性を保つために何をする必要がありますか?

4

1 に答える 1

5

UsernamePasswordToken ソースを参照してください。

class UsernamePasswordToken extends AbstractToken
{

    /**
     * Constructor.
     *
     * @param string|object            $user        The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method.
     * @param string                   $credentials This usually is the password of the user
     * @param string                   $providerKey The provider key
     * @param RoleInterface[]|string[] $roles       An array of roles
     *
     * @throws \InvalidArgumentException
     */
    public function __construct($user, $credentials, $providerKey, array $roles = array())

特に $user パラメータの説明に

@param string|object $user ユーザー名 (ニックネーム、電子メール アドレスなど)、または UserInterface インスタンスまたはオブジェクト

したがって、アプリの使用法では、ユーザー エンティティを $user パラメータとして渡していますが、テストではメール文字列を渡しています。

したがって、最初の方法は、新しいユーザー オブジェクトを作成し、それにテスト データを入力するか、次のようにリポジトリから特定のユーザーを取得することです。

$user = $client->getContainer()->get('doctrine')->getManager()->getRepository('MyAppUserBundle:User')->findOneByEmail('norbert.scrunge@gmail.com');
$token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_USER', 'ROLE_ADMIN'));
于 2015-05-19T22:17:39.353 に答える