DB-less PHPUnit tests
This page is for application creators who write unit tests that run anywhere in seconds. Exponential's phpunit.xml
loads tests/bootstrap.php, which loads Composer's autoloader and the test toolkit but does not boot the kernel; tests
that need nothing else run without a database (PHPUnit).
Contents
What to test without a database
| Code | Example assertions |
|---|---|
| Services with pure logic | a report's totals, an import's parsing |
| Validators | accepted and refused inputs, error texts |
| Datatype string forms | fromString( toString( x ) ) gives x |
| Template operators | modify() sets the expected value |
| Settings parsing | defaults when a key is missing |
| Security helpers | escaping, allow lists, redirect checks |
Keep database access out of these classes, or behind an interface you can replace in the test.
A test class
// extension/expdemo/tests/expDemoColorValidatorTest.php
class expDemoColorValidatorTest extends PHPUnit\Framework\TestCase
{
public function testAcceptsHexColors()
{
$this->assertTrue( expDemoColorValidator::isValid( '#a1b2c3' ) );
}
public function testRefusesOtherText()
{
$this->assertFalse( expDemoColorValidator::isValid( 'red; background: url(x)' ) );
}
}Loading your classes
Classes in the extension autoload map are found once php bin/php/ezpgenerateautoloads.php -e has run. A test that runs
in a separate checkout can require_once the class file when it is not autoloadable, as the kernel's own help tests do
(tests/tests/kernel/classes/help/).
Running
vendor/bin/phpunit extension/expdemo/tests/
vendor/bin/phpunit --filter testRefusesOtherText extension/expdemo/tests/Run it in your extension's CI on every push and pull request (Continuous integration for extensions).
Mapping tests to files
The kernel keeps tests/test-map.json, which maps source files to the tests that cover them, so a change runs only its
own tests before a push. Do the same in a large extension: a small map file and a script that picks the tests of the
changed files.
Related pages
- Testing applications
- Testing and CI standard
- PHPUnit versions
- Free documentation: this page is free to copy, translate and improve under the GNU FDL 1.3.
Become an Exponential Partner
Partners share their information, provide funding, contribute back and develop the products with us, and that is how Exponential grows. A partner website and dashboard are planned for mid-2027: please become a partner today to speed up our growth rate and land new features faster.