PHP   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了symfony – FOSUserBundle – PHPUnit – 模拟用户大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Symfony和FOSUserBundle,现在我喜欢测试一些东西:

>学说生命周期
>防火墙后的控制器

对于那些测试,我需要是特定用户或至少在用户组中.
如何模拟用户会话以便

>像“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 – 模拟用户全部内容,希望文章能够帮你解决symfony – FOSUserBundle – PHPUnit – 模拟用户所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。