在PHPUnit中运行特定的测试套件时,如何跳过运行缓慢的测试,而在需要完整的代码覆盖时仍然运行所有测试?

时间:2019-09-24 20:58:10

标签: unit-testing configuration phpunit phpunit-testing

我有一个测试套件,在我的PHPUnit配置中标有。该测试套件包含各种测试,并且还具有数据库密集型实时数据库测试,这些测试需要很长时间才能完成。

特别是其中一项测试需要2秒钟才能完成(请参见下文)。

我想运行的快速测试与慢速测试分开,以便在我有更多时间时可以运行完整的慢速但完整的测试版本,但总的来说,我想运行快速测试满足我的日常需求,从而省去了运行测试服时的缓慢测试。

我该怎么做?

为了记录,我的phpunit.xml配置如下:

<phpunit bootstrap="bootstrap.php">
    <testsuite name="Crating">
        <directory>../module/Crating/test/</directory>
    </testsuite>
</phpunit>

我用来运行测试套件的命令如下:

phpunit -c phpunit.xml --testsuite CratingCalc

我的../module/Crating/test/目录中的文件之一是CrateRepositoryTest.php。看起来像这样:

class CrateRepositoryTest extends TestCase
{

    function testCombine()
    {
        //mocked up hardcoded data
        $fake = new FakeCratingDataModel();

        //connection to real live database
        $real = new CratingDataModel();    

        /* 
         * Tests that verify mocked up data to match live data
         * Purpose to have them is to alert me when live database data or schema change
         */
        $this->assertEquals($fake->getContentsBySalesOrderNumber(7777), $real->getContentsBySalesOrderNumber(7777));
        $this->assertEquals($fake->getContentsByShopJobNumber(17167), $real->getContentsByShopJobNumber(17167));
        $this->assertEquals($fake->getNearCrating(20, 20, 20), $real->getNearCrating(20, 20, 20));
        $this->assertEquals($fake->getContentsByInquiryNumber(640, 2), $real->getContentsByInquiryNumber(25640, 2));
    }
}

1 个答案:

答案 0 :(得分:1)

组。

通常,您可以添加注释@group small或有@group ci(仅用于在完全CI环境中运行的注释)。

事实上,进行小型,中型或大型测试非常普遍,有专用的组注释-@small, @medium & @large,并且phpunit.xml文件也有一些设置,这些设置还可以为每个设置提供时间限制(如果花费的时间太长,将会杀死它们并使它们失败):

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  ....
  timeoutForLargeTests="5"
  timeoutForMediumTests="2"
  timeoutForSmallTests="1"
  .... >

我有两种运行测试的方法-不排除任何组的完整版本(运行 1250个测试大约需要50秒,没有覆盖范围),以及添加{{ 1}}到phpunit命令中,该命令可以在不到 4秒的时间内运行630个测试。