簡體   English   中英

PHPUnit - 我可以根據 PHP 版本運行測試嗎?

[英]PHPUnit - Can I run tests depending on PHP version?

我正在編寫一個應該與 PHP 5.3+ 一起使用的庫。 我想使用生成器和閉包綁定,但這些功能是 5.5+ 和 5.4+。 大多數 lib 可以在沒有這些功能的情況下工作,因此我只想在 php 具有正確版本時運行某些單元測試。 有沒有一種簡單的方法可以做到這一點?

我正在尋找這樣的東西:

/** @version 5.4+*/
public function testUsingClosureBind(){...}

/** @version 5.5+*/
public function testUsingGenerators(){...}

但我願意接受任何建議......

歸檔此問題的一種正確方法是使用 @group 注釋您的測試,具體取決於該功能適用​​的版本:

/**
 * @group 5.4
 */
public function testUsingClosureBind() {...}

/**
 * @group 5.5
 */
public function testUsingGenerators() {...}

現在你可以執行屬於某個組的測試,或者忽略一個組:

phpunit --group 5.5
phpunit --group 5.4
phpunit --exclude-group 5.5

PHPUnit 網站上的文檔

自 PHPUnit 3.7 起(至少)@requires注釋支持

<?php

use PHPUnit\Framework\TestCase;

final class SomeTest extends TestCase
{
    /**
     * @requires PHP 5.3
     */
    public function testSome()
    {
    }
}

有關更多信息,請參閱文檔

使用 version_compare 函數 ( http://us3.php.net/manual/en/function.version-compare.php )。 舉個例子 :

public function testSomething() {
    if (version_compare(PHP_VERSION, '5.0', '>=')) {
        //do tests for PHP version 5.0 and higher
    } else {
        //do different tests for php lower than 5.0
    }
 }

我知道這不是 phpunit 測試組織的最佳實踐,但是如果您能夠根據所需的 php 版本在不同的文件中使用這些方法,則可以在 XML 配置文件中使用以下內容:

   <testsuites>
    <testsuite name="My Test Suite">
      <directory suffix="Test.php" phpVersion="5.3.0" phpVersionOperator=">=">/path/to/files</directory>
      <file phpVersion="5.3.0" phpVersionOperator=">=">/path/to/MyTest.php</file>
    </testsuite>
  </testsuites>

(見http://phpunit.de/manual/3.7/en/appendixes.configuration.html#appendixes.configuration.testsuites

根據 Sebastian 的說法,我應該使用@requires 注釋來做到這一點。 它不能用組完成,因為我不能根據 php 版本自動排除它們。

順便提一句。 它沒有幫助,因為我在 5.3 版之前總是遇到解析錯誤,因為使用了yield::class ...

他建議將依賴於版本的代碼移動到另一個文件並使用這個:

<testsuite name="My Test Suite">
  <directory suffix="Test.php" phpVersion="5.3.0" phpVersionOperator=">=">/path/to/files</directory>
  <file phpVersion="5.3.0" phpVersionOperator=">=">/path/to/MyTest.php</file>
</testsuite>

該文件不應位於/path/to/files目錄下,除非您希望將其包含在內...

最后,我為與更高 php 版本相關的測試添加了 2 個新后綴:

    <testsuite name="unit tests">
        <directory suffix="Test.php" phpVersion="5.3.0" phpVersionOperator=">=">test/unit</directory>
        <directory suffix="Test54.php" phpVersion="5.4.0" phpVersionOperator=">=">test/unit</directory>
        <directory suffix="Test55.php" phpVersion="5.5.0" phpVersionOperator=">=">test/unit</directory>
    </testsuite>

暫無
暫無

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

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