symfony – FOSUserBundle – PHPUnit – 模拟用户
发布时间:2020-12-13 13:54:08 所属栏目:PHP教程 来源:网络整理
导读:我正在使用Symfony和FOSUserBundle,现在我喜欢测试一些东西: 学说生命周期 防火墙后的控制器 对于那些测试,我需要是特定用户或至少在用户组中. 如何模拟用户会话以便… 像“createdAt”这样的生命周期字段将使用登录用户 Controller就像一些模拟用户登录一
我正在使用Symfony和FOSUserBundle,现在我喜欢测试一些东西:
>学说生命周期 对于那些测试,我需要是特定用户或至少在用户组中. >像“createdAt”这样的生命周期字段将使用登录用户 例: 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 AcmeMyBundleDataFixturesORM; use DoctrineCommonDataFixturesAbstractFixture; use DoctrineCommonDataFixturesFixtureInterface; use DoctrineCommonPersistenceObjectManager; use AcmeMyBundleEntityUser; 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( 'AcmeMyBundleDataFixturesORMLoadUserData',)); $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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |