簡體   English   中英

您可以從腳本運行 PHPUnit 測試嗎?

[英]Can you run PHPUnit tests from a script?

我有一個 PHP 部署腳本,我想先運行 PHPUnit 測試,如果測試失敗就停止。 我一直在谷歌上搜索這個,很難找到關於從 php 運行單元測試的文檔,而不是從命令行工具。

對於最新版本的 PHPUnit,您可以執行以下操作:

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

最好是不需要我手動指定每個測試套件的解決方案。

弄清楚了:

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

最簡單的方法是實例化類 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 文件中。 如果您需要不同的格式,您可以查看文檔 您還可以通過更改傳遞給 run 方法的數組來添加更多選項。

使用 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()

等等...

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

PHP7 & phpunit ^7 解決方案

use PHPUnit\TextUI\Command;

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

與 CLI 命令的效果相同:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM