PHPackages                             tomwilford/doctrine-test-traits - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. tomwilford/doctrine-test-traits

ActiveLibrary[Testing &amp; Quality](/categories/testing)

tomwilford/doctrine-test-traits
===============================

Traits to facilitate database integration tests with doctrine/dbal and doctrine/migrations

v1.0.0(today)00MITPHPPHP ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0CI passing

Since Jun 27Pushed todayCompare

[ Source](https://github.com/TomWilford/doctrine-test-traits)[ Packagist](https://packagist.org/packages/tomwilford/doctrine-test-traits)[ RSS](/packages/tomwilford-doctrine-test-traits/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (6)Versions (3)Used By (0)

doctrine-test-traits
====================

[](#doctrine-test-traits)

[![QA & Tests](https://github.com/TomWilford/doctrine-test-traits/actions/workflows/tests.yml/badge.svg)](https://github.com/TomWilford/doctrine-test-traits/actions/workflows/tests.yml)[![PHP Version](https://camo.githubusercontent.com/beb56501a8abb1c4640f473217abda3cbdb5668937edab89fd94beb4f3382cc1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d254532253839254135253230382e322532302d2d253230382e352d3838393262662e737667)](https://php.net)[![License](https://camo.githubusercontent.com/2028f05e1eda69a25431b407dbfb59906074863a4f4c2b9c2a271c77f50d6ee4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f546f6d57696c666f72642f646f637472696e652d746573742d747261697473)](LICENSE)

Traits to facilitate database integration tests with ephemeral databases using `doctrine/dbal` and `doctrine/migrations`.

The aim is to provide helper methods that can create, populate and destroy database tables for use in integration tests, leveraging doctrine libraries.

This was heavily inspired by [selective/test-traits](https://packagist.org/packages/selective/test-traits) and [samuelgfeller/test-traits](https://packagist.org/packages/samuelgfeller/test-traits).

Installation
------------

[](#installation)

```
composer require tomwilford/doctrine-test-traits --dev
```

This will install the library (and `doctrine/dbal` and `doctrine/migrations` if you haven't installed them yet).

Usage
-----

[](#usage)

Warning

This library relies on a `doctrine/migrations` class that is marked as internal (`MigratorConfiguration`). The use of this class is confirmed as working with `3.9.7`, but the behaviour could change in a later version and break this.

### Migrations

[](#migrations)

In a phpunit test, create an instance of the `DatabaseTestContext` class in the `setUp` method, with your doctrine connection and the relevant config loader for your application.

If you are working with a [driver that supports in-memory instances](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.4/reference/configuration.html#connection-details), you should use prefer that option. Alternatively create a new database for your driver (e.g. `my_test_db`) and ensure you use that name when creating the connection to avoid making changes to your dev environment database.

```
private DatabaseTestContext $context;

protected function setUp(): void
{
    $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]);
    $migrationsConfig = new PhpFile('/path/to/migrations.php');

     $this->context = new DatabaseTestContext(
        $connection,
        $migrationsConfig,
    );
}
```

This example uses the `migrations.php` that `doctrine/migrations` expects at the root of your project, but all of these are valid:

```
// json
$migrationsConfig = new \Doctrine\Migrations\Configuration\Migration\JsonFile('/path/to/migrations.json');

// yaml
$migrationsConfig = new \Doctrine\Migrations\Configuration\Migration\YamlFile('/path/to/migrations.yml');

// xml
$migrationsConfig = new \Doctrine\Migrations\Configuration\Migration\XmlFile('/path/to/migrations.xml');

// raw array
$migrationsConfig = new \Doctrine\Migrations\Configuration\Migration\ConfigurationArray([
    'table_storage' => [
        // etc
    ],
    // etc
]);
```

Next, use `DatabaseTestTrait` in the test case and implement its methods in `setUp` and `tearDown`.

```
use TomWilford\DoctrineTestTraits\Trait\DatabaseTestTrait;

protected function setUp(): void
{
    // configure DatabaseTestContext

    $this->setUpDatabase($this->context);
}

protected function tearDown(): void
{
    $this->tearDownDatabase($this->context);

    parent::tearDown();
}
```

`doctrine-test-traits` will find your migration classes from your `doctrine/migrations` configuration and run them up to the `latest` version alias before each test method is executed; then drop each table after each test method is executed.

### Fixtures

[](#fixtures)

To populate your test database with data your integration tests can interact with...

Create a class that implements `DatabaseTestFixtureInterface` and populate the methods. Make sure the array keys you use line up with the names of your table's columns.

```
class TestTableFixture implements DatabaseTestFixtureInterface
{
    public function getTableName(): string
    {
        return 'test_table';
    }

    public function getRecordsToInsert(): array
    {
        return [
            [
                'id' => 1,
                'value' => 'Record 1',
            ],
            [
                'id' => 99,
                'value' => 'Record 99',
            ],
        ];
    }
}
```

Instantiate the concrete fixture when configuring your `DatabaseTestContext` and pass it to the context, within an instance of `DatabaseTestFixtureDto`. `DatabaseTestFixtureDto` can accept as many `DatabaseTestFixtureInterface` instances as you require

```
protected function setUp(): void
{
    // configure DatabaseTestContext

     $this->context = new DatabaseTestContext(
        $connection,
        $migrationsConfig,
        new DatabaseTestFixtureDto(
            new TestTableFixture()//, new OtherTableFixture()
        )
    );
}
```

### Recommendation

[](#recommendation)

To centralise the configuration of `DatabaseTestContext` and to automatically apply the database actions to `setUp`/`tearDown` it is recommended to create your own `AppTestTrait` (or whatever you want to call it) as a wrapper for `DatabaseTestTrait` and use that in your unit tests.

```
trait AppTestTrait
{
    use DatabaseTestTrait;

    // store the configuration as a static instance to share between test cases
    protected static ?DatabaseTestContext $context = null;

    // automatically configure setUp, no need to implement this in your test case
    protected function setUp(): void
    {
        $this->setUpDatabase($this->createContext());
    }

    // automatically configure tearDown, no need to implement this in your test case
    protected function tearDown(): void
    {
        $this->tearDownDatabase($this->createContext());

        parent::tearDown();
    }

    protected function createContext(): DatabaseTestContext
    {
        if (!self::$context) {
            // configure your connection and migrations config here
            $connection = DriverManager::getConnection([...]);
            $config = new ConfigurationArray([...]);

            self::$context = new DatabaseTestContext(
                $connection,
                $config,
                new DatabaseTestFixtureDto(
                    new TestTableFixture()
                )
            );
        }

        return self::$context;
    }
}
```

### Performance

[](#performance)

For performance with a large database/lots of migrations you may want to consider running `DatabaseTestTrait`'s methods in `setUpBeforeClass` and `tearDownAfterClass`.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

42

—

FairBetter than 89% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

0d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a82b2ac25a173ec4556a091b046ee9a269060f5a8d0a2b13eb3d4e490fee5fa5?d=identicon)[jollyBlueMan](/maintainers/jollyBlueMan)

---

Top Contributors

[![TomWilford](https://avatars.githubusercontent.com/u/28453594?v=4)](https://github.com/TomWilford "TomWilford (4 commits)")

---

Tags

phpunittestdoctrinetraits

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tomwilford-doctrine-test-traits/health.svg)

```
[![Health](https://phpackages.com/badges/tomwilford-doctrine-test-traits/health.svg)](https://phpackages.com/packages/tomwilford-doctrine-test-traits)
```

###  Alternatives

[zenstruck/foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.

79513.1M132](/packages/zenstruck-foundry)[ta-tikoma/phpunit-architecture-test

Methods for testing application architecture

10953.8M18](/packages/ta-tikoma-phpunit-architecture-test)[php-mock/php-mock-phpunit

Mock built-in PHP functions (e.g. time()) with PHPUnit. This package relies on PHP's namespace fallback policy. No further extension is needed.

1718.7M509](/packages/php-mock-php-mock-phpunit)[ergebnis/phpunit-slow-test-detector

Provides facilities for detecting slow tests in phpunit/phpunit.

1489.3M94](/packages/ergebnis-phpunit-slow-test-detector)[zenstruck/assert

Standalone, lightweight, framework agnostic, test assertion library.

8216.4M10](/packages/zenstruck-assert)[colinodell/psr-testlogger

PSR-3 compliant test logger based on psr/log v1's, but compatible with v2 and v3 too!

1813.2M67](/packages/colinodell-psr-testlogger)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
