Quick and simple unit-testing without a test-framework.
I wanted a simple, single-file unit-test that I can package and distribute with components - and I agree with Go language philosophy of testing and their non-framework approach.
There's nothing to deploy or integrate here - it's just a few global functions, and you should feel free to modify these and tailor them specifically to suit the test-requirements for your solution.
Runs in a browser or on the command-line.
See this project for real-world use and integration with Travis CI.
Command-line output from example.php
looks something like this:
> php.exe /path/to/my/test.php
=== Describe your test here ===
- PASS: OK
- PASS: because it's true
- PASS: TRUE
- PASS: just because (TRUE)
- PASS: because the bar() method will throw (RuntimeException)
Process finished with exit code 0
To implement code coverage reporting, import the php-code-coverage
package from your composer.json
:
...
"require-dev": {
"phpunit/php-code-coverage": "2.0.*@dev"
}
...
Be sure to include the Composer autoloader in your test-script:
/** @var \Composer\Autoload\ClassLoader $autoloader */
$autoloader = require __DIR__ . '/vendor/autoload.php';
You may also wish to configure the autoloader with your namespace.
Before doing your tests, initialize the code coverage run-time:
if (coverage()) {
$filter = coverage()->filter();
// whitelist the files to cover:
$filter->addFileToWhitelist(__DIR__ . '/src/Foo.php');
$filter->addFileToWhitelist(__DIR__ . '/src/Bar.php');
coverage()->setProcessUncoveredFilesFromWhitelist(true);
// start code coverage:
coverage()->start('test');
}
Now do your tests, and then finally output the results:
if (coverage()) {
// stop code coverage:
coverage()->stop();
// output code coverage report to console:
$report = new PHP_CodeCoverage_Report_Text(10, 90, false, false);
echo $report->process(coverage(), false);
// output code coverage report for integration with CI tools:
$report = new PHP_CodeCoverage_Report_Clover();
$report->process(coverage(), __DIR__ . '/build/logs/clover.xml');
}
Be sure to copy/paste the coverage()
function from below.
If you wish to relay all PHP errors/warnings/notices to exceptions, add the following:
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
$error = new ErrorException($errstr, 0, $errno, $errfile, $errline);
if ($error->getSeverity() & error_reporting()) {
throw $error;
}
});