1. 项目协同
  2. 代码仓库
  3. DevOps 实践之旅
  4. 一分钟开始持续集成之旅
  5. 持续部署
  6. 制品库

PHP 自动化测试

Laravel 8 框架使用 PHPUnit 9 作为默认的单元测试组件,适用于 PHP 7.3 及更高版本。

PHPUnit 可生成 HTML、Clover 等格式的测试覆盖率报告,JUnit 等格式的测试结果,但不支持检查测试覆盖率大小,可通过 「phpunit-coverage-check」进行检查。

安装

在代码目录执行命令进行安装:

$ composer require --dev phpunit/phpunit
$ composer require --dev rregeer/phpunit-coverage-check

编写测试代码

按照 Laravel 官方文档,编写测试代码。

业务代码(app/Http/Controllers/Welcome.php):

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class Welcome extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        return view('welcome');
    }
}

路由(routes/web.php):

use Illuminate\Support\Facades\Route;

Route::get('/', \App\Http\Controllers\Welcome::class);

测试代码(app/Http/Controllers/Welcome.php):

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

本地运行

本地运行测试,将会生成「JUnit 格式测试结果」和「HTML 和 Clover 格式覆盖率报告」。

$ ./vendor/bin/phpunit --coverage-html storage/reports/tests/ --coverage-clover storage/reports/tests/clover.xml --log-junit storage/test-results/junit.xml tests/

$ head storage/test-results/junit.xml
$ open storage/reports/tests/index.html

根据 Clover 报告检查测试覆盖率,如果不达标,将会报错退出:

$ ./vendor/bin/coverage-check storage/reports/tests/clover.xml 80
  Total code coverage is 53.85 % which is below the accepted 80%
$ echo $?
  1

持续集成

pipeline {
  stages {
    stage("检出") {
      steps {
        checkout([$class: "GitSCM", branches: [[name: env.GIT_BUILD_REF]],
        userRemoteConfigs: [[url: env.GIT_REPO_URL, credentialsId: env.CREDENTIALS_ID]]])
      }
    }
    stage('准备环境') {
      steps {
        sh 'update-alternatives --set php /usr/bin/php8.0'
        sh 'apt-get install -y php8.0-sqlite php8.0-xdebug'
        sh 'echo "xdebug.mode=coverage" >> /etc/php/8.0/cli/conf.d/20-xdebug.ini'
        sh 'composer install'
        sh 'touch database/database.sqlite'
      }
    }
    stage("测试") {
      steps {
        sh "XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html storage/reports/tests/ --coverage-clover storage/reports/tests/clover.xml --log-junit storage/test-results/junit.xml --coverage-text tests/"
        sh 'vendor/bin/coverage-check storage/reports/tests/clover.xml 80'
      }
      post {
        // 不管成功失败,都收集简易测试结果
        always {
          junit "storage/test-results/junit.xml"
        }
        // 成功时,收集测试覆盖率报告
        success {
          codingHtmlReport(name: "测试覆盖率报告", path: "storage/reports/tests/")
        }
      }
    }
  }
}




上一篇Java 自动化测试
最近更新
感谢反馈有用
感谢反馈没用

在阅读中是否遇到以下问题?

您希望我们如何改进?