1. 授权认证
  2. 获取用户个人信息
  3. 项目协同
  4. 代码托管
  5. 持续集成
  6. 制品仓库
  7. 测试管理
  8. 文档管理
  1. 项目协同
  2. 代码仓库
  3. DevOps 实践之旅
  4. 一分钟开始持续集成之旅
  5. 持续部署
  6. 制品库

PHP 自动化测试

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

安装

如果使用其他框架,执行下列命令进行安装:

$ composer require --dev phpunit/phpunit

$ ./vendor/bin/phpunit --help
PHPUnit 9.3.10 by Sebastian Bergmann and contributors.

Usage:
  phpunit [options] UnitTest.php
  phpunit [options] directory

Code Coverage Options:
  --coverage-clover file    Generate code coverage report in Clover XML format
  --coverage-html dir       Generate code coverage report in HTML format
  --coverage-xml dir        Generate code coverage report in PHPUnit XML format

Logging Options:
  --log-junit file          Log test execution in JUnit XML format to file
  --log-teamcity file       Log test execution in TeamCity format to file

PHPUnit 可生成 HTML、Clover 等格式的测试覆盖率报告,JUnit 等格式的测试结果。

编写测试代码

按照 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 格式覆盖率报告」。

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

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

持续集成

pipeline {
  agent {
    docker {
      image "php:8.0-cli"
      args "-v /root/.composer:/root/.composer"
      registryCredentialsId ""
      reuseNode true
    }
  }
  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 "composer install"
      }
    }
    stage("测试") {
      steps {
        sh "./vendor/bin/phpunit --coverage-html storage/reports/tests/ --log-junit storage/test-results/junit.xml tests/"
      }
      post {
        // 不管成功失败,都收集简易测试结果
        always {
          junit "storage/test-results/junit.xml"
        }
        // 成功时,才会生成测试覆盖率报告,进行收集
        success {
          codingHtmlReport(name: "测试覆盖率报告", path: "storage/reports/tests/")
        }
      }
    }
  }
}



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