【问题标题】:Can you run PHPUnit tests from a script?您可以从脚本运行 PHPUnit 测试吗?
【发布时间】:2013-02-24 11:56:24
【问题描述】:

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

对于最新版本的 PHPUnit,你可以这样做:

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

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

【问题讨论】:

  • PHPUnit 附带源代码。您可以take a look into the testrunner 它包含从脚本运行 phpunit 的代码。
  • 好提示!是否有任何预先实现的方法来收集我要运行的所有测试套件?
  • 我有点惊讶这不是一件很常见的事情。在执行诸如部署之类的操作时,是否有更好的方法可以自动运行所有单元测试?
  • 当然可以,只要运行:phpunit ./dir/to/your/tests

标签: php phpunit


【解决方案1】:

想通了:

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

【讨论】:

  • 在上面的示例中,我们如何从 $test_results 对象中获取文本报告的详细信息?
  • 当我测试时,我只有一个例外是设置或测试有问题,而不是单元测试失败,所以$test_results即使在测试失败时也可用。
【解决方案2】:

最简单的方法是实例化 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 方法的数组来添加更多选项。

【讨论】:

    【解决方案3】:

    使用 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】:

      PHP7 & phpunit ^7 解决方案

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

      与 CLI 命令的效果相同:

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

      【讨论】:

      • 如何获取输出?就像我想象的那样,从代码运行 phpunit 的原因是然后发送一封带有“x 失败,y 已通过”的电子邮件或其他东西显然
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 2016-10-25
        • 1970-01-01
        • 1970-01-01
        • 2014-11-17
        • 1970-01-01
        • 2015-05-08
        • 2019-01-19
        • 1970-01-01
        相关资源
        最近更新 更多