Rust-style doc tests for PHP. Write executable code examples in your docblocks or as PHP attributes, and run them as PHPUnit tests.
- PHP 8.4+
- PHPUnit 12.0+
composer require monadial/phpunit-docrunnerWrite PHP code blocks in docblocks or use #[DocTest] attributes:
class Calculator
{
/**
* ```php
* $result = Calculator::add(2, 3);
* self::assertEquals(5, $result);
* ```
*/
public static function add(int $a, int $b): int
{
return $a + $b;
}
}use Monadial\DocRunner\Attribute\DocTest;
class Calculator
{
#[DocTest(<<<'PHP'
$result = Calculator::add(2, 3);
self::assertEquals(5, $result);
PHP)]
public static function add(int $a, int $b): int
{
return $a + $b;
}
}Run:
vendor/bin/doctest run --directory=srcvendor/bin/doctest run [--directory=src] [--no-cache] [--phpunit-binary=...]
vendor/bin/doctest generate [--directory=src] [--no-cache]
vendor/bin/doctest lint [--directory=src] [--no-cache]- run (default) — generate tests and run them with PHPUnit
- generate — generate test files without running
- lint — generate and syntax-check without running
All commands accept --directory (repeatable), --config, and --no-cache.
Add to phpunit.xml for automatic integration:
<extensions>
<bootstrap class="Monadial\DocRunner\Integration\PHPUnit\DocTestExtension">
<parameter name="directories" value="src/" />
<parameter name="cache-dir" value=".doctest-cache/" />
</bootstrap>
</extensions>
<testsuites>
<testsuite name="DocTests">
<directory>.doctest-cache/generated</directory>
</testsuite>
</testsuites>The extension generates tests during bootstrap and warns if the generated directory isn't in your test suite config.
Optional doctest.xml for project defaults:
<?xml version="1.0"?>
<doctest>
<directories>
<directory>src/</directory>
</directories>
<exclude>
<pattern>*Test.php</pattern>
</exclude>
<cache-dir>.doctest-cache/</cache-dir>
<bootstrap>vendor/autoload.php</bootstrap>
</doctest>Source files are parsed via AST (nikic/php-parser) — no files are require-ed. Code blocks are extracted from docblocks and #[DocTest] attributes, then generated as PHPUnit TestCase classes. Each source file produces one test class; each code block becomes one test method. Namespace and imports carry over from the source file.
Generated tests are cached by content hash. Unchanged files are skipped on subsequent runs.
MIT
