我正在使用Symfony和FOSUserBundle,现在我喜欢测试一些东西:
>学说生命周期
>防火墙后的控制器
对于那些测试,我需要是@R_404_359@或至少在用户组中.
如何模拟用户会话以便…
>像“createdAt”这样的生命周期字段将使用登录用户
> Controller就像一些模拟用户登录一样
例:
class FooTest extends ... { function setUp() { $user = $this->getMock('User',['getId','getName']); $someWhereGlobal->user = $user; // after this you should be logged in as a mocked user // all operations should run using this user. } }
您可以使用
LiipFunctionalTestBundle执行此操作.一旦安装并配置了Bundle,就可以轻松创建和用户并登录测试.
为您的用户创建一个夹具
这将创建一个将在测试期间加载的用户:
<?PHP // Filename: DataFixtures/ORM/LoadUserData.PHP namespace Acme\MyBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Acme\MyBundle\Entity\User; class LoadUserData extends AbstractFixture implements FixtureInterface { public function load(ObjectManager $manager) { $user = new User(); $user ->setId(1) ->setName('foo bar') ->setEmail('foo@bar.com') ->setPassword('12341234') ->setAlgorithm('plaintext') ->setEnabled(true) ->setConfirmationToken(null) ; $manager->persist($user); $manager->flush(); // Create a reference for this user. $this->addReference('user',$user); } }
如果要使用用户组,可以看到official documentation.
如LiipFunctionalTestBundle’s documentation中所述,以下是如何在数据库中加载用户并以此用户身份登录:
/** * Log in as the user defined in the Data Fixture. */ public function testWithUserLoggedIn() { $fixtures = $this->loadFixtures(array( 'Acme\MyBundle\DataFixtures\ORM\LoadUserData',)); $repository = $fixtures->getReferenceRepository(); // Get the user from its reference. $user = $repository->getReference('user') // You can perform operations on this user. // ... // And perform functional tests: // Create a new Client which will be logged in. $this->loginAs($user,'YOUR_FIREWALL_NAME'); $this->client = static::makeClient(); // The user is logged in: do whatever you want. $path = '/'; $crawler = $this->client->request('GET',$path); }