سؤال

I'm working in some tests for my code and I get my first "STOP" since I don't know how to mover forward on this. See in my setUp() function I load fixtures:

public function setUp() {
    static::$kernel = static::createKernel();
    static::$kernel->boot();
    $this->em = static::$kernel->getContainer()->get('doctrine')->getManager();
    $this->user = $this->createUser();

    $fix = new MetaDetailGroupFixtures();
    $fix->load($this->em);

    parent::setUp();
}

But then I have remove that created data since I have a test for the bad case (when not entities are returned):

public function testListMetaDetailGroupFailAction() {
    $client = static::createClient();
    $this->logIn($client, $this->user);

    $route = $client->getContainer()->get('router')->generate('meta-detail-group-list', array('parent_id' => 20000), false);
    $client->request("GET", $route);

    $decoded = json_decode($client->getResponse()->getContent(), true);

    $this->assertCount(0, $decoded['entities']);
    $this->assertArrayHasKey('success', $decoded);
    $this->assertJsonStringEqualsJsonString(json_encode(array("success" => false, "message" => "No existen grupos de metadetalles de productos creados")), $client->getResponse()->getContent());
    $this->assertSame(200, $client->getResponse()->getStatusCode());
    $this->assertSame('application/json', $client->getResponse()->headers->get('Content-Type'));
    $this->assertNotEmpty($client->getResponse()->getContent());
}

Since records are created in setup and they remain in DB that test fail. Any advice on this? How did yours solve that?

هل كانت مفيدة؟

المحلول

There is no easy way to do what you ask. What is normally done is truncating the database before and after executing your tests so you have a truly clean and isolated environment.

Quoting from this nice article (http://blog.sznapka.pl/fully-isolated-tests-in-symfony2/:

public function setUp()
{
    $kernel = new \AppKernel("test", true);
    $kernel->boot();
    $this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
    $this->_application->setAutoExit(false);
    $this->runConsole("doctrine:schema:drop", array("--force" => true));
    $this->runConsole("doctrine:schema:create");
    $this->runConsole("doctrine:fixtures:load", array("--fixtures" => __DIR__ . "/../DataFixtures"));
}

As you can see, this solution makes use of Doctrine's Symfony2 commands in order to achieve the isolation state. There is a bundle I like to use which solves exactly this problem and let you use nice ready to use FunctionalTest base classes and many other features. Check it out:

https://github.com/liip/LiipFunctionalTestBundle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top