intaro/symfony-testing-tools

Symfony测试工具

v0.1 2016-03-25 08:42 UTC

This package is auto-updated.

Last update: 2024-09-14 23:56:55 UTC


README

该库包含了改进的WebTestCase和Container类,便于进行测试。

特性

客户端本地缓存

Web客户端在WebTestCase中进行缓存。如果你想要获取一个客户端,你应该使用

$client = static::getClient();

如果你想要获取一个新的客户端,你应该使用

$client = static::getClient(true);

完整示例

<?php
namespace Foo\BarBundle\Tests\Controller;

use Intaro\SymfonyTestingTools\WebTestCase;

class SomeControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::getClient(true);
        //...
    }
}

EntityManager和Container的快捷方式

你可以在当前上下文中直接获取EntityManager或Container

<?php
namespace Foo\BarBundle\Tests\Controller;

use Intaro\SymfonyTestingTools\WebTestCase;

class SomeControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::getClient(true);
        
        $em = static::getEntityManager();
        $service = static::getContainer()->get('some_service');
        //...
    }
}

检查响应HTTP代码

你可以使用以下方法检查响应结果

<?php

namespace Foo\BarBundle\Tests\Controller;

use Intaro\SymfonyTestingTools\WebTestCase;

class SomeControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::getClient();

        $client->request('GET', '/foo/bar/index');
        $this->assertResponseOk($client->getResponse(), 'Page opens');
        $this->assertResponseRedirect($client->getResponse(), 'Page redirects to other page');
        $this->assertResponseNotFound($client->getResponse(), 'Page not found');
        $this->assertResponseForbidden($client->getResponse(), 'Page forbidden');
        $this->assertResponseCode(201, $client->getResponse(), 'JSON returned', 'application/json');
    }
}

添加固定值

你可以在测试运行之前添加固定值

<?php

namespace Foo\BarBundle\Tests\Controller;

use Foo\BarBundle\DataFixtures\ORM\Test\ActionRecordData;
use Intaro\SymfonyTestingTools\WebTestCase;

class SomeControllerTest extends WebTestCase
{
    public static function setUpBeforeClass()
    {
        static::appendFixture(new ActionRecordData, [
            'purge' => true,
        ]);
    }

    public function testIndex()
    {
        //...
    }
}