gpt4 book ai didi

symfony - FOSUserBundle - PHPUnit - 模拟用户

转载 作者:行者123 更新时间:2023-12-02 13:21:46 25 4
gpt4 key购买 nike

我正在将 Symfony 与 FOSUserBundle 一起使用,现在我想测试一些东西,例如:

  • Doctrine 生命周期
  • 防火墙后面的 Controller

对于这些测试,我需要是特定用户或至少是用户组中的用户。如何模拟用户 session 以便...

  • 像“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);
}

关于symfony - FOSUserBundle - PHPUnit - 模拟用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com