An open API service indexing awesome lists of open source software.

https://github.com/cspray/database-testing-phpunit

A testing extension for cspray/database-testing to setup a database for testing with PHPUnit
https://github.com/cspray/database-testing-phpunit

php8 phpunit-extension

Last synced: 12 days ago
JSON representation

A testing extension for cspray/database-testing to setup a database for testing with PHPUnit

Awesome Lists containing this project

README

          

# cspray/database-testing-phpunit

A PHPUnit Extension for [cspray/database-testing](https://github.com/cspray/database-testing), designed to facilitate setting up a test database suitable for automated testing.

## Installation

Composer is the only supported method for installing this library.

```shell
composer require --dev cspray/database-testing-phpunit
```

Please note, it is highly likely you'll need a library that provides an implementation of `Cspray\DatabaseTesting\ConnectionAdapter\ConnectionAdapter`! This library does not come with the adapter appropriate for your database connection!

## Review the tests!

If you're here to learn more about how to use `cspray/databse-testing` in your PHPUnit tests, check out the tests in this library! The `phpunit.xml` config and the implemented tests provide a working example on how to use it!

## Quick Start

The examples below uses a `ConnectionAdapter` and `ConnectionAdapterFactory` available from `cspray/database-testing-pdo`. If PDO is not an appropriate connection for your use case, please replace with the appropriate `ConnectionAdapter` implementation.

### Register your Extension

The first step is to register the extension in your PHPUnit configuration. Ensure the following XML is present in `phpunit.xml` (or the file you use for you PHPUnit config).

```xml

```

### Attribute your TestCase

The next step is to add the `#[RequiresTestDatabase]` attribute to your PHPUnit TestCase. There's no inheritance or traits required, you don't need to change what `TestCase` you extend!

```php
loadFixtures([
new SingleRecordFixture('my_table', ['name' => 'from setup'])
]);
}

#[LoadFixture(
new SingleRecordFixture('my_table', ['name' => 'from attribute'])
)]
public function testTableHasCorrectRecords() : void {
$table = self::$testDatabase->table('my_table');

self::assertCount(2, $table);
self::assertSame('from attribute', $table->row(0)->get('name'));
self::assertSame('from setup', $table->row(1)->get('name'));
}

}
```

Generally speaking, I would not recommend mixing approaches to loading fixtures. Either use the `#[LoadFixture]` Attribute, or use `TestDatabase` helper in your setup or test methods.