对于遇到这个问题的人,我发布了一个从这里开始找到的解决方案(https://www.sitepoint.com/quick-tip-testing-symfony-apps-with-a-disposable-database/)以及一些调查和反复试验:
教义会议
#api/config/packages/test/doctrine.yaml
doctrine:
dbal:
driver: 'pdo_sqlite'
memory: true
charset: UTF8
Run Code Online (Sandbox Code Playgroud)
带数据库的Web测试用例
<?php
namespace App\Tests;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Metadata\ClassMetadata;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class WebTestCaseWithDatabase extends WebTestCase
{
/**
* @var KernelBrowser
*/
protected $client;
/**
* @var EntityManager
*/
protected $em;
/**
* @var SchemaTool
*/
protected $schemaTool;
/**
* @var ClassMetadata[]
*/
protected $metaData;
protected function setUp()
{
parent::setUp();
// This is tricky. You need to boot the kernel to create the DDBB.
// But if you boot it with static::bootKernel(),
// an error will be thrown if you create the client in your tests,
// because static::createClient() tries boot again the kernel.
// That's why I create the client and boot the kernel only once here.
$this->client = static::createClient();
// Make sure we are in the test environment
if ('test' !== self::$kernel->getEnvironment()) {
throw new \LogicException('Tests cases with fresh database must be executed in the test environment');
}
// Get the entity manager from the service container
$this->em = self::$kernel->getContainer()->get('doctrine')->getManager();
// Run the schema update tool using our entity metadata
$this->metaData = $this->em->getMetadataFactory()->getAllMetadata();
$this->schemaTool = new SchemaTool($this->em);
$this->schemaTool->updateSchema($this->metaData);
}
// Helper function to add fixtures
public function addFixture($className)
{
$loader = new Loader();
$loader->addFixture(new $className);
$purger = new ORMPurger($this->em);
$executor = new ORMExecutor($this->em, $purger);
$executor->execute($loader->getFixtures());
}
// Trunkate the whole database on tearDown
protected function tearDown(): void
{
parent::tearDown();
// Purge all the fixtures data when the tests are finished
$purger = new ORMPurger($this->em);
// Purger mode 2 truncates, resetting autoincrements
$purger->setPurgeMode(2);
$purger->purge();
}
}
Run Code Online (Sandbox Code Playgroud)
示例测试
<?php
namespace App\Tests;
use App\DataFixtures\ExampleFixture;
class ExampleTest extends WebTestCaseWithDatabase
{
protected function setUp()
{
parent::setUp();
// Add whatever fixtures you need here
$this->addFixture(ExampleFixture::class);
}
// Add your tests
public function test_something()
{
// test code
}
}
Run Code Online (Sandbox Code Playgroud)
我希望它有帮助!