Skip to content

Commit ffa46be

Browse files
committed
Improve tests to ensure extension handles robust testing scenarios
1 parent 4abb147 commit ffa46be

9 files changed

+283
-6
lines changed

.github/workflows/ci.yml

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
name: 'Tests'
2+
3+
on:
4+
push:
5+
branches: [main]
6+
pull_request:
7+
branches: [main]
8+
9+
jobs:
10+
unit-testing:
11+
runs-on: ubuntu-latest
12+
13+
steps:
14+
- uses: actions/checkout@v3
15+
- name: Setup PHP
16+
uses: shivammathur/setup-php@v2
17+
with:
18+
php-version: 8.3
19+
extensions: xdebug
20+
tools: composer:2
21+
- name: Setup problem matchers for PHP
22+
run: echo "::add-matcher::${{ runner.tool_cache }}/php.json"
23+
- name: Setup problem matchers for PHPUnit
24+
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
25+
- name: Composer
26+
run: composer install
27+
- name: Unit Testing
28+
env:
29+
XDEBUG_MODE: coverage
30+
run: ./vendor/bin/phpunit

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
.phpunit.cache
2-
vendor/
2+
vendor/
3+
composer.lock

README.md

Lines changed: 130 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,133 @@ Composer is the only supported method for installing this library.
88

99
```shell
1010
composer require --dev cspray/database-testing-phpunit
11-
```
11+
```
12+
13+
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!
14+
15+
16+
## Review the tests!
17+
18+
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!
19+
20+
## Quick Start
21+
22+
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.
23+
24+
### Register your Extension
25+
26+
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).
27+
28+
```xml
29+
<extensions>
30+
<bootstrap class="Cspray\DatabaseTesting\PhpUnit\DatabaseTestingExtension" />
31+
</extensions>
32+
```
33+
34+
### Attribute your TestCase
35+
36+
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!
37+
38+
```php
39+
<?php declare(strict_types=1);
40+
41+
namespace Cspray\DatabaseTesting\PhpUnit\Demo;
42+
43+
use Cspray\DatabaseTesting\DatabaseCleanup\TransactionWithRollback;
44+
use Cspray\DatabaseTesting\Pdo\Sqlite\SqliteConnectionAdapterFactory;
45+
use Cspray\DatabaseTesting\PhpUnit\RequiresTestDatabase;
46+
use PHPUnit\Framework\TestCase;
47+
48+
#[RequiresTestDatabase(
49+
new SqliteConnectionAdapterFactory(
50+
':memory:',
51+
'/path/to/my/schema'
52+
),
53+
new TransactionWithRollback()
54+
)]
55+
final class MyDemoTest extends TestCase {
56+
57+
}
58+
```
59+
60+
### Inject the TestDatabase
61+
62+
To work with your test database there is a helper class with the type, `Cspray\DatabaseTesting\TestDatabase`. This object allows accessing the underlying test database connection, load fixtures, and access the data in a given table.
63+
64+
This object is managed by the extension. It is created when your TestCase has started, before any tests or setup have run. This property MUST BE static, the extension does not have access to the TestCase instance that is running.
65+
66+
```php
67+
<?php declare(strict_types=1);
68+
69+
namespace Cspray\DatabaseTesting\PhpUnit\Demo;
70+
71+
use Cspray\DatabaseTesting\DatabaseCleanup\TransactionWithRollback;
72+
use Cspray\DatabaseTesting\Pdo\Sqlite\SqliteConnectionAdapterFactory;
73+
use Cspray\DatabaseTesting\PhpUnit\InjectTestDatabase;use Cspray\DatabaseTesting\PhpUnit\RequiresTestDatabase;
74+
use Cspray\DatabaseTesting\TestDatabase;use PHPUnit\Framework\TestCase;
75+
76+
#[RequiresTestDatabase(
77+
new SqliteConnectionAdapterFactory(
78+
':memory:',
79+
'/path/to/my/schema'
80+
),
81+
new TransactionWithRollback()
82+
)]
83+
final class MyDemoTest extends TestCase {
84+
85+
#[InjectTestDatabase]
86+
private static TestDatabase $testDatabase;
87+
88+
}
89+
```
90+
91+
### Load Fixtures and Run Test
92+
93+
In our example, we're going to load tests both in `setUp` and as an attribute on a given test. This example is meant to show in what order fixtures get ran, and to show that there are alternatives to loading fixtures if you do not like attributes.
94+
95+
```php
96+
<?php declare(strict_types=1);
97+
98+
namespace Cspray\DatabaseTesting\PhpUnit\Demo;
99+
100+
use Cspray\DatabaseTesting\DatabaseCleanup\TransactionWithRollback;
101+
use Cspray\DatabaseTesting\Fixture\LoadFixture;use Cspray\DatabaseTesting\Fixture\SingleRecordFixture;use Cspray\DatabaseTesting\Pdo\Sqlite\SqliteConnectionAdapterFactory;
102+
use Cspray\DatabaseTesting\PhpUnit\InjectTestDatabase;
103+
use Cspray\DatabaseTesting\PhpUnit\RequiresTestDatabase;
104+
use Cspray\DatabaseTesting\TestDatabase;
105+
use PHPUnit\Framework\TestCase;
106+
107+
#[RequiresTestDatabase(
108+
new SqliteConnectionAdapterFactory(
109+
':memory:',
110+
'/path/to/my/schema'
111+
),
112+
new TransactionWithRollback()
113+
)]
114+
final class MyDemoTest extends TestCase {
115+
116+
#[InjectTestDatabase]
117+
private static TestDatabase $testDatabase;
118+
119+
protected function setUp() : void{
120+
parent::setUp(); // TODO: Change the autogenerated stub
121+
self::$testDatabase->loadFixtures([
122+
new SingleRecordFixture('my_table', ['name' => 'from setup'])
123+
]);
124+
}
125+
126+
#[LoadFixture(
127+
new SingleRecordFixture('my_table', ['name' => 'from attribute'])
128+
)]
129+
public function testTableHasCorrectRecords() : void {
130+
$table = self::$testDatabase->table('my_table');
131+
132+
self::assertCount(2, $table);
133+
self::assertSame('from attribute', $table->row(0)->get('name'));
134+
self::assertSame('from setup', $table->row(1)->get('name'));
135+
}
136+
137+
}
138+
```
139+
140+
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.

composer.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "cspray/database-testing-phpunit",
3-
"description": "",
3+
"description": "A testing extension for cspray/database-testing to integrate with PHPUnit.",
44
"require": {
55
"php": "^8.3",
66
"cspray/database-testing": "dev-main",
@@ -18,5 +18,8 @@
1818
"psr-4": {
1919
"Cspray\\DatabaseTesting\\PhpUnit\\Tests\\": "tests"
2020
}
21+
},
22+
"suggest": {
23+
"cspray/database-testing-pdo": "dev-main"
2124
}
2225
}

phpunit.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
<testsuite name="default">
1717
<directory>tests</directory>
1818
</testsuite>
19+
<testsuite name="phpt">
20+
<directory suffix=".phpt">tests</directory>
21+
</testsuite>
1922
</testsuites>
2023

2124
<source ignoreIndirectDeprecations="true" restrictNotices="true" restrictWarnings="true">

src/DatabaseTestingExtension.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ public function __construct(
4444

4545
public function notify(Started $event) : void {
4646
$firstTest = $event->testSuite()->tests()->asArray()[0];
47+
if (!$firstTest->isTestMethod()) {
48+
return;
49+
}
4750
assert($firstTest instanceof TestMethod);
4851

4952
$reflection = new \ReflectionClass($firstTest->className());
@@ -88,7 +91,7 @@ public function __construct(
8891
) {}
8992

9093
public function notify(PreparationStarted $event) : void {
91-
if ($this->data->cleanupStrategy !== null && $event->test()->isTestMethod()) {
94+
if ($this->data->connectionAdapter !== null) {
9295
$testMethod = $event->test();
9396
assert($testMethod instanceof TestMethod);
9497
$test = FixtureAttributeAwareDatabaseTest::fromTestMethodWithPossibleFixtures(
@@ -109,7 +112,7 @@ public function __construct(
109112
) {}
110113

111114
public function notify(TestFinished $event) : void {
112-
if ($this->data->cleanupStrategy !== null && $event->test()->isTestMethod()) {
115+
if ($this->data->cleanupStrategy !== null) {
113116
$testMethod = $event->test();
114117
assert($testMethod instanceof TestMethod);
115118
$test = FixtureAttributeAwareDatabaseTest::fromTestMethodWithPossibleFixtures(
@@ -130,11 +133,13 @@ public function __construct(
130133
) {}
131134

132135
public function notify(TestSuiteFinished $event) : void {
133-
if (!$event->testSuite()->isForTestClass() || $this->data->connectionAdapter === null) {
136+
if ($this->data->connectionAdapter === null) {
134137
return;
135138
}
136139

137140
$this->data->connectionAdapter->closeConnection();
141+
$this->data->connectionAdapter = null;
142+
$this->data->cleanupStrategy = null;
138143
}
139144
};
140145
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Cspray\DatabaseTesting\PhpUnit\Tests\Integration;
4+
5+
use Cspray\DatabaseTesting\DatabaseCleanup\TransactionWithRollback;
6+
use Cspray\DatabaseTesting\Fixture\LoadFixture;
7+
use Cspray\DatabaseTesting\Fixture\SingleRecordFixture;
8+
use Cspray\DatabaseTesting\Pdo\Sqlite\SqliteConnectionAdapterFactory;
9+
use Cspray\DatabaseTesting\PhpUnit\DatabaseTestingExtension;
10+
use Cspray\DatabaseTesting\PhpUnit\InjectTestDatabase;
11+
use Cspray\DatabaseTesting\PhpUnit\RequiresTestDatabase;
12+
use Cspray\DatabaseTesting\TestDatabase;
13+
use PHPUnit\Framework\Attributes\CoversClass;
14+
use PHPUnit\Framework\TestCase;
15+
16+
#[CoversClass(DatabaseTestingExtension::class)]
17+
#[RequiresTestDatabase(
18+
new SqliteConnectionAdapterFactory(
19+
initialSchemaPath: __DIR__ . '/../../resources/schemas/sqlite.sql'
20+
),
21+
new TransactionWithRollback()
22+
)]
23+
final class LoadFixtureInSetupIntegrationTest extends TestCase {
24+
25+
#[InjectTestDatabase]
26+
private static TestDatabase $testDatabase;
27+
28+
protected function setUp() : void {
29+
self::$testDatabase->loadFixtures([
30+
new SingleRecordFixture('my_table', ['name' => 'from setup'])
31+
]);
32+
}
33+
34+
public function testTableHasRecordLoadedFromSetup() : void {
35+
$table = self::$testDatabase->table('my_table');
36+
37+
self::assertCount(1, $table);
38+
self::assertSame('from setup', $table->row(0)->get('name'));
39+
}
40+
41+
#[LoadFixture(
42+
new SingleRecordFixture('my_table', ['name' => 'from attribute'])
43+
)]
44+
public function testTableHasRecordsLoadedFromSetupLoadFixtureAndFromAttribute() : void {
45+
$table = self::$testDatabase->table('my_table');
46+
47+
self::assertCount(2, $table);
48+
self::assertSame('from attribute', $table->row(0)->get('name'));
49+
self::assertSame('from setup', $table->row(1)->get('name'));
50+
}
51+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Cspray\DatabaseTesting\PhpUnit\Tests\Integration;
4+
5+
use Cspray\DatabaseTesting\DatabaseCleanup\TransactionWithRollback;
6+
use Cspray\DatabaseTesting\Fixture\LoadFixture;
7+
use Cspray\DatabaseTesting\Fixture\SingleRecordFixture;
8+
use Cspray\DatabaseTesting\Pdo\Sqlite\SqliteConnectionAdapterFactory;
9+
use Cspray\DatabaseTesting\PhpUnit\DatabaseTestingExtension;
10+
use Cspray\DatabaseTesting\PhpUnit\InjectTestDatabase;
11+
use Cspray\DatabaseTesting\PhpUnit\RequiresTestDatabase;
12+
use Cspray\DatabaseTesting\TestDatabase;
13+
use PHPUnit\Framework\Attributes\CoversClass;
14+
use PHPUnit\Framework\Attributes\DataProvider;
15+
use PHPUnit\Framework\TestCase;
16+
17+
#[CoversClass(DatabaseTestingExtension::class)]
18+
#[RequiresTestDatabase(
19+
new SqliteConnectionAdapterFactory(
20+
initialSchemaPath: __DIR__ . '/../../resources/schemas/sqlite.sql'
21+
),
22+
new TransactionWithRollback()
23+
)]
24+
final class UsesDataProviderIntegrationTest extends TestCase {
25+
26+
#[InjectTestDatabase]
27+
private static TestDatabase $testDatabase;
28+
29+
public static function recordData() : array {
30+
return [
31+
'first' => [0, 'first record'],
32+
'second' => [1, 'second record']
33+
];
34+
}
35+
36+
#[DataProvider('recordData')]
37+
#[LoadFixture(
38+
new SingleRecordFixture('my_table', ['name' => 'first record']),
39+
new SingleRecordFixture('my_table', ['name' => 'second record'])
40+
)]
41+
public function testLoadFixturesWithTestThatUsesDataProvider(int $row, string $name) : void {
42+
$table = self::$testDatabase->table('my_table');
43+
44+
self::assertCount(2, $table);
45+
self::assertSame($name, $table->row($row)->get('name'));
46+
}
47+
48+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
--TEST--
2+
Ensure .phpt tests run with no extension errors
3+
--FILE--
4+
<?php
5+
echo 'cspray/database-testing';
6+
--EXPECT--
7+
cspray/database-testing

0 commit comments

Comments
 (0)