Charles
Charles

Reputation: 1039

Can you run PHPUnit tests from a script?

I have a PHP deployment script that I want to run PHPUnit tests first, and stop if the tests fail. I've been googling this a lot, and it's very hard to find documentation on running unit tests from php, rather than from the command line tool.

For the newest version of PHPUnit, can you do something like:

$unit_tests = new PHPUnit('my_tests_dir');
$passed = $unit_tests->run();

Preferably a solution that doesn't require me to manually specify each test suite.

Upvotes: 12

Views: 6803

Answers (5)

Budkovsky
Budkovsky

Reputation: 21

Solution for PHP7 & phpunit ^7

use PHPUnit\TextUI\Command;

$command = new Command();
$command->run(['phpunit', 'tests']);

Does the same effect as CLI command:

vendor/bin/phpunit --bootstrap vendor/autoload.php tests

Upvotes: 2

myxaxa
myxaxa

Reputation: 1381

working with PHPUnit 7.5:

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;

$test = new TestSuite();
$test->addTestSuite(MyTest::class);
$result = $test->run();

and $result object contains lot of usefull data:

$result->errors()
$result->failures
$result->wasSuccessful()

etc...

Upvotes: 3

alexw
alexw

Reputation: 8668

It doesn't seem like PHPUnit has any built-in configuration to prevent it from dumping its output directly into the response (at least not as of PHPUnit 5.7).

So, I used ob_start to shunt output to a variable, and set the third argument of doRun to false to prevent PHPUnit from halting the script:

<?php

$suite = new PHPUnit_Framework_TestSuite();
$suite->addTestSuite('App\Tests\DatabaseTests');

// Shunt output of PHPUnit to a variable
ob_start();
$runner = new PHPUnit_TextUI_TestRunner;
$runner->doRun($suite, [], false);
$result = ob_get_clean();

// Print the output of PHPUnit wherever you want
print_r($result);

Upvotes: 0

Bojan Dević
Bojan Dević

Reputation: 1875

Simplest way to do this is by instantiating object of class PHPUnit_TextUI_Command.

So here is an example:

require '/usr/share/php/PHPUnit/Autoload.php';

function dummy($input)
{
   return '';
}

//Prevent PHPUnit from outputing anything
ob_start('dummy');

//Run PHPUnit and log results to results.xml in junit format
$command = new PHPUnit_TextUI_Command;
$command->run(array('phpunit', '--log-junit', 'results.xml', 'PHPUnitTest.php'),
              true);

ob_end_clean();

This way the results will be logged in results.xml file in junit format that can be parsed. If you need a different format you can check the documentation. Also you can add more options by changing the array passed to run method.

Upvotes: 6

Charles
Charles

Reputation: 1039

Figured it out:

$phpunit = new PHPUnit_TextUI_TestRunner;

try {
    $test_results = $phpunit->dorun($phpunit->getTest(__DIR__, '', 'Test.php'));
} catch (PHPUnit_Framework_Exception $e) {
    print $e->getMessage() . "\n";
    die ("Unit tests failed.");
}

Upvotes: 7

Related Questions