我正在编写新的Behat测试。新的背景从头开始。
Scenario: user visualization
Given database is empty
Class "AppBundle\Entity\User" sub class of "FOS\UserBundle\Model\User" is not a valid entity or mapped super class. (Doctrine\ORM\Mapping\MappingException)
步骤如下:
/** @Given database is empty */
public function databaseIsEmpty()
{
$this->manager->createQuery('delete from AppBundle\Entity\User')->execute();
}
上下文实现了KernelAwareContext,它允许上下文加载内核,从而也加载了doctrine。
class Context implements BehatContext, KernelAwareContext
{
private $kernel;
public function setKernel(KernelInterface $kernel)
{
$this->kernel = $kernel;
$this->client = new \GuzzleHttp\Client([
'base_uri' => 'http://localhost:8001',
]);
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/../../AppBundle/Entity"), true);
$conn = array('driver' => 'pdo_sqlite', 'path' => __DIR__ . '/../../../data/data.sqlite',);
$this->manager = EntityManager::create($conn, $config);
}
但......
调用$this->manager->createQuery('delete from AppBundle\Entity\User')->execute();
时,返回错误Class "AppBundle\Entity\User" sub class of "FOS\UserBundle\Model\User" is not a valid entity or mapped super class.
相同的查询,在单元测试中执行。这里唯一的区别是单元测试以这种方式加载:
public function setUp()
{
$this->client = static::createClient();
self::bootKernel();
$this->container = self::$kernel->getContainer();
$this->manager = $this->container->get('doctrine.orm.entity_manager');
$this->manager->createQuery('delete from AppBundle\Entity\User')->execute();
}
答案 0 :(得分:2)
如果您的实体映射,设置等问题首先需要进行排序。我给你完整的工作示例,所以你需要使用它。第一个清除数据库中的每个表,而第二个清除只有一个表。
PURGE WHOLE DATABASE
use Behat\MinkExtension\Context\MinkContext;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Component\HttpKernel\KernelInterface;
class FeatureContext extends MinkContext implements KernelAwareContext
{
/** @var KernelInterface */
private $kernel;
public function setKernel(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* @Given /^the database is empty$/
*/
public function theDatabaseIsEmpty()
{
$container = $this->kernel->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
$purger = new ORMPurger();
$purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE);
$executor = new ORMExecutor($entityManager, $purger);
$executor->execute([]);
}
}
清除单一实体
/**
* @Given /^there is no user in database$/
*/
public function thereIsNoUserInDatabase()
{
$container = $this->kernel->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
// AppBundle\Entity\User.php
$entityManager->createQuery('DELETE FROM AppBundle:User')->execute();
}