Symfony 2 + Доктрина 2 + phpunit 3.5: сериализация исключения закрытия

StackOverflow https://stackoverflow.com/questions/4366592

  •  09-10-2019
  •  | 
  •  

Вопрос

Я пытался найти что-то об этом в Google, но ничего не вышел. У меня есть класс тестовогостата, который наследует из Webtestcase, с некоторыми методами, которые я хочу использовать во всех моих модулях / функциональных тестах:

<?php

namespace Application\FaxServerBundle\Test;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;

use Application\FaxServerBundle\DataFixtures\ORM\NetworkConfigurationData;

class TestCase extends WebTestCase
{
    protected $kernel;

    public function setUp()
    {
        parent::setUp();
    }

    public function getEm()
    {
        return $this->getService( 'doctrine.orm.entity_manager' );
    }

    public function getNetworkConfigurationRepository()
    {
        return $this->getEm()->getRepository( 'Application\FaxServerBundle\Entity\NetworkConfiguration' );
    }

    public function loadNetworkConfigurationFixtures()
    {
        $loader = new Loader();
        $loader->addFixture( new NetworkConfigurationData() );

        $this->loadFixtures( $loader );
    }

    public function loadFixtures( $loader )
    {
        $purger     = new ORMPurger();
        $executor   = new ORMExecutor( $this->getEm(), $purger );
        $executor->execute( $loader->getFixtures() );
    }

    protected function getService( $name, $kernel = null )
    {
        return $this->getBootedKernel()->getContainer()->get( $name );
    }

    protected function hasService( $name, $kernel = null )
    {

        return $this->getBootedKernel()->getContainer()->has( $name );
    }

    protected function getBootedKernel()
    {
        $this->kernel = $this->createKernel();

        if ( !$this->kernel->isBooted() ) 
        {
            $this->kernel->boot();
        }

        return $this->kernel;
    }

    public function generateUrl( $client, $route, $parameters = array() )
    {
        return $client->getContainer()->get( 'router' )->generate( $route, $parameters );
    }
}

Затем мой модуль тест:

<?php

namespace Application\FaxServerBundle\Tests\Entity;

use Doctrine\ORM\AbstractQuery;

use Application\FaxServerBundle\Entity;
use Application\FaxServerBundle\Test\TestCase;

class NetworkConfigurationRepositoryTest extends TestCase
{
 public function setUp()
 {
  parent::setUp();

  $this->loadNetworkConfigurationFixtures();
 }

 public function testGetConfiguration()
 {
  $config = $this->getNetworkConfigurationRepository()->getConfigurationArray();

  $this->assertInternalType( 'array', $config );
  $this->assertEquals( 6, count( $config ) );
  $this->assertArrayHasKey( 'id', $config );
  $this->assertArrayHasKey( 'ip', $config );
  $this->assertArrayHasKey( 'gateway', $config );
  $this->assertArrayHasKey( 'subnetMask', $config );
  $this->assertArrayHasKey( 'primaryDns', $config );
  $this->assertArrayHasKey( 'secondaryDns', $config );
 }

 public function testGetConfigurationObject()
 {
  $config = $this->getNetworkConfigurationRepository()->getConfigurationObject();

  $this->assertInternalType( 'object', $config );
 }

 public function testGetConfigurationArray()
 {
  $config = $this->getNetworkConfigurationRepository()->getConfigurationArray();

  $this->assertInternalType( 'array', $config );
 }
}

Раньше он работал, но, внезапно, после того, как я обновил своих поставщиков (учение включено), он начал бросать это исключение:

3) Application\FaxServerBundle\Tests\Entity\NetworkConfigurationRepositoryTest::testGetConfigurationArray
RuntimeException: PHP Fatal error:  Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances' in -:32
Stack trace:
#0 [internal function]: PDO->__sleep()
#1 -(32): serialize(Array)
#2 -(113): __phpunit_run_isolated_test()
#3 {main}

Next exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in -:0
Stack trace:
#0 -(0): serialize()
#1 -(113): __phpunit_run_isolated_test()
#2 {main}
  thrown in - on line 0

Я обнаружил, что проблема исходит из загрузки прибора. Если я удалю код, который загружает приспособления, он работает.

Кто-нибудь знает, что может быть неправильно в моем коде? Это лучший способ загрузки светильников?

Спасибо!

Это было полезно?

Решение

Не технически связано с вашим вопросом. Тем не менее, у меня было очень трудно, пытаясь решить «сериализацию« закрытия »не допускается« проблемой при использовании phpunit, и этот вопрос - лучший результат Google.

Проблема исходит от того факта, что phpunit сериализует все $ глобали в системе, чтобы определить их, пока запущен тест. Затем он восстанавливает их после проведения теста.

Однако, если у вас есть какие-либо закрытия в вашем глобальном пространстве, он собирается вызвать проблемы. Есть два способа решения этого.

Вы можете полностью отключить глобальную процедуру резервной копии, используя аннотацию.

/**
 * @backupGlobals disabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    // ...
}

Или, если вы знаете, какая переменная вызывает проблему (ищите лямбда в var_dump ($ Globals)), вы можете просто заблокировать переменную (ы) задачи.

class MyTest extends PHPUnit_Framework_TestCase
{
    protected $backupGlobalsBlacklist = array('application');
    // ...
}

Другие советы

Вы также можете попробовать.

<phpunit backupGlobals="false">
    <testsuites>
        <testsuite name="Test">
            <directory>.</directory>
        </testsuite>
    </testsuites>
</phpunit>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top