phpunit中执行指定测试case的方法

一. 问题

一个测试文件中,可能包含多个case,如何只执行其中的某个或某几个case呢?

比如下面的这段测试代码(demotest.php),是否可以只执行针对FuncA的两个测试~testFuncA_1,testFuncA_2呢?

<?php
use PHPUnit\Framework\TestCase;

class Unittest_Demo extends TestCase{
    public function testFuncA_1(){
        echo "\nFuncA1 test\n";
        $this->assertTrue(true);
    }
    
    public function testFuncA_2(){
        echo "\nFuncA2 test\n";
        $this->assertTrue(true);
    }

    public function testFuncB_1(){
        echo "\nFuncB1 test\n";
        $this->assertTrue(true);
    }

    public function testFuncB_2(){
        echo "\nFuncB2 test\n";
        $this->assertTrue(true);
    }
}

二. 解决

2.1 方法一 @group

可以用 @group 标注来标记某个case属于一个或多个组,就像这样:

class MyTest extends PHPUnit_Framework_TestCase{
    /**
     * @group specification
     */
    public function testSomething(){
    }

    /**
     * @group regresssion
     * @group bug2204
     */
    public function testSomethingElse(){
    }
}

测试可以基于组来选择性的执行,使用命令行phpunit的 --group选项+组名,可以执行对应测试组的测试。

对于1中的问题,我们可以做如下标注:

class Unittest_Demo extends TestCase{
    /** 
     *@group FuncA
     * */
    public function testFuncA_1(){
        ... ...
    }
    /** 
     *@group FuncA
     * */
    public function testFuncA_2(){
         ... ...
    }
    
    ...

执行

phpunit test.php --group FuncA

得到结果

PHPUnit 6.5.3 by Sebastian Bergmann and contributors.

.
FuncA1 test
.                                                              2 / 2 (100%)
FuncA2 test


Time: 88 ms, Memory: 8.00MB

OK (2 tests, 2 assertions)

可以使用–list-group选项,查看文件中存在的group。
比如针对上例,我们执行的效果如下:

phpunit test.php --list-group
PHPUnit 6.5.3 by Sebastian Bergmann and contributors.

Available test group(s):
 - FuncA
 - default

default分组就是未特别标识的case(testFuncB_1,testFuncB_2)。有需要,你可以使用如下命令执行这些case。

phpunit test.php --group default

特别注意

@group是以注释的形式存在,注释的第一行必须是/**,否则phpunit将不识别。

2.2 方法二 --filter

命令行的phpunit支持如下选项:

扫描二维码关注公众号,回复: 5817312 查看本文章
--filter <pattern> 

可以用于筛选满足条件的用例。

对于1中的问题,我们可以执行通过如下命令达到目的。

phpunit test.php --filter FuncA 

注意,pattern部分类似于mysql的like,即%FuncA%。因此命中了名为testFuncA_1,testFuncA_2的两个case。

猜你喜欢

转载自blog.csdn.net/qmhball/article/details/88692584