loading fixtures with Symfony 5 in a WebTestCase

Viewed 685

How do you load fixtures before running a WebTestCase in Symfony 5 ?

Which methods do you use without installing any additional bundles?

class MyPageControllerTest extends WebTestCase
{
    public function testIndexAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());

        $table = $crawler->filter('.table-emp');

        $this->assertCount(1, $table->filter('tbody tr'));
    }
}
1 Answers

WebTestCase extends Symfony's KernelTestCase which extends PHPUnit's TestCase. PhpUnit has few important methods.

// executed once before the first test
public static void setUpBeforeClass();

// executed once before the last test
public static void tearDownAfterClass();

// executed once for every test before it starts
public void setUp();

// executed once for every test after it ends
public void tearDown();

If you want to have a fresh test database for every test I would create a bash script that executes MySQL file and gets your data in place. Doing it like that gives you so much control over what is happening and where.

I think that to create something reusable and consistent you could create your own Test Case that could extend existing Symfony Web Test case.

This way you will gain one extra abstraction layer in which you can put all the fixture set up and all other extra functionality that might be needed across you web (or API if you do the same for API) tests.

Another solution that would not require using extra class could involve traits and putting your functions there.

I would personally recommend custom parent class with some traits that hold functionality that could be shared between different kinds of tests like


class MyAwesomeParentTestClass 
{
    use AwesomeFeatureTrait;
    use CustomAssertionsTrait;
}

I know you don't want to use extra bundles so this is just an extra suggestion. In case you decide to use bundle, I would recommend using this: Alice.

Related