airmedia/phpunit-doctrine-extension

提供功能ORM/DB测试的基础TestCase。

0.10.1 2021-07-02 14:37 UTC

This package is auto-updated.

Last update: 2024-08-29 04:46:46 UTC


README

提供功能ORM\DB测试的基础TestCase。

支持RDBMS

  • PostgreSQL > 9.4
  • SQLite

安装

$ composer require airmedia\phpunit-doctrine-extension --dev

支持PostgreSQL

为了与PostgreSQL一起工作,您需要修改PHPUnit的配置文件(phpunit.xml),为PHPUnit添加一些变量以配置到PostgreSQL服务器的连接。例如

    <php>
        <var name="db_type" value="pdo_pgsql" />
        <var name="db_host" value="localhost" />
        <var name="db_username" value="postgres" />
        <var name="db_password" value="" />
        <var name="db_name" value="my_database_tests" />
        <var name="db_port" value="5432" />
    </php>

如果缺少这些选项,则将使用SQLite作为后备驱动程序。

使用方法

您必须从AirMedia\Test\OrmTestCase继承,并实现createMappingDriver来提供配置的映射驱动程序。

您还可以重写静态字段$customTypes来为Doctrine定义自定义类型。

示例

<?php

use AirMedia\Test\ORMTestCase;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
use Doctrine\ORM\Configuration;
use Ramsey\Uuid\Doctrine\UuidType;

class RepositoryTestCase extends ORMTestCase
{
    static protected $customTypes = [
        UuidType::NAME => UuidType::class,
    ];
    
    public function testAnything()
    {
        $repository = $this->em->getRepository('Acme\Entity\User');
        
        // Action and asserts...
    }
    
    protected function createMappingDriver(Configuration $config): MappingDriver
    {
        $annotationDriver = $config->newDefaultAnnotationDriver([
            realpath(__DIR__ . '/../src/Entity'),
        ], false);
        
        $driver = new MappingDriverChain();
        $driver->addDriver($annotationDriver, 'Acme\Entity');

        return $driver;
    }
}

Doctrine数据固定扩展

您可以使用特质AirMedia\Test\Helper\DataFixturesTrait通过数据固定填充您的数据库。

<?php

use AirMedia\Test\ORMTestCase;
use AirMedia\Test\Helper\DataFixturesTrait;

class FooTestCase extends ORMTestCase
{
    use DataFixturesTrait;
    
    protected function setUp()
    {
        parent::setUp();
        
        $this->loadFixtures([
            new \Acme\DataFixtures\UserFixture(),
            'Acme\DataFixtures\GroupFixture', // or class name
        ]);
    }
}

许可

本软件包使用MIT许可证授权。