你能从脚本运行PHPUnit测试吗?

时间:2013-03-08 20:11:44

标签: php phpunit

我有一个PHP部署脚本,我想先运行PHPUnit测试,如果测试失败则停止。我一直在谷歌搜索这个,很难找到关于从php运行单元测试的文档,而不是从命令行工具。

对于最新版本的PHPUnit,您可以执行以下操作:

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

最好是一种不需要我手动指定每个测试套件的解决方案。

5 个答案:

答案 0 :(得分:7)

想出来:

$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.");
}

答案 1 :(得分:5)

最简单的方法是实例化PHPUnit_TextUI_Command类的对象。

所以这是一个例子:

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();

这样结果将以junit格式记录在results.xml文件中,可以解析。如果您需要其他格式,可以查看documentation。您还可以通过更改传递给run方法的数组来添加更多选项。

答案 2 :(得分:0)

似乎PHPUnit没有任何内置配置来阻止它将输出直接转储到响应中(至少不是PHPUnit 5.7)。

因此,我使用ob_start将输出分流到变量,并将doRun的第三个参数设置为false以防止PHPUnit暂停脚本:

<?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);

答案 3 :(得分:0)

使用PHPUnit 7.5:

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

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

和$ result对象包含许多有用的数据:

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

等...

答案 4 :(得分:0)

PHP7和phpunit ^ 7的解决方案

use PHPUnit\TextUI\Command;

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

与CLI命令具有相同的作用:

vendor/bin/phpunit --bootstrap vendor/autoload.php tests
相关问题