温馨提示×

Laravel在Linux上的测试如何进行

小樊
42
2025-11-02 11:17:15
栏目: 智能运维

1. 准备Linux环境
在Linux系统上运行Laravel测试前,需确保已安装以下核心组件:

  • PHP:Laravel 10.x要求PHP 8.0及以上版本,需安装常用扩展(如mbstringopensslpdo_mysqltokenizerxmlgdbcmath等)。可通过包管理器安装(如Ubuntu/Debian使用sudo apt install php php-cli php-mbstring php-openssl php-pdo-mysql php-tokenizer php-xml php-gd php-bcmath,CentOS使用sudo yum install php php-mbstring php-openssl php-pdo php-mysqlnd php-tokenizer php-xml php-gd php-bcmath)。
  • Composer:PHP依赖管理工具,用于安装Laravel框架及项目依赖。通过curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer全局安装,验证composer --version输出版本号。
  • Web服务器:推荐使用Nginx(高性能)或Apache(兼容性好),需配置虚拟主机指向项目public目录(Nginx配置示例:server { listen 80; server_name yourdomain.com; root /path/to/laravel/public; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } })。
  • 数据库:Laravel支持MySQL、PostgreSQL等,需安装对应数据库服务并创建数据库(如MySQL:CREATE DATABASE laravel_test; CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'your_password'; GRANT ALL PRIVILEGES ON laravel_test.* TO 'laravel_user'@'localhost'; FLUSH PRIVILEGES;)。

2. 配置Laravel项目

  • 创建/克隆项目:通过Composer创建新项目(composer create-project --prefer-dist laravel/laravel your_project_name)或克隆现有项目(git clone https://github.com/laravel/laravel.git your_project_name)。
  • 配置环境变量:复制.env.example.envcp .env.example .env),修改数据库连接信息(DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=laravel_testDB_USERNAME=laravel_userDB_PASSWORD=your_password),并通过php artisan key:generate生成应用密钥(.envAPP_KEY需为base64:开头的随机字符串)。
  • 设置文件权限:Laravel的storage(日志、缓存、上传文件)和bootstrap/cache(配置缓存)目录需Web服务器用户(如www-data)可写。执行sudo chown -R www-data:www-data /path/to/laravel(将项目所有者设为Web用户),sudo chmod -R 775 /path/to/laravel/storagesudo chmod -R 775 /path/to/laravel/bootstrap/cache(设置目录权限)。

3. 安装PHPUnit
Laravel默认集成PHPUnit,无需单独安装。若需升级或重新安装,可通过Composer执行composer require --dev phpunit/phpunit。项目根目录下的phpunit.xml文件用于配置PHPUnit(如测试目录、输出格式、测试数据库等),默认已配置好基本设置。

4. 编写测试用例
Laravel的测试目录为tests/,分为Unit(纯单元测试)和Feature(功能测试/集成测试):

  • 创建测试类:使用Artisan命令生成。单元测试用php artisan make:test ExampleUnitTest --unit(生成tests/Unit/ExampleUnitTest.php,继承Tests\Unit\TestCase,不加载Laravel环境);功能测试用php artisan make:test ExampleFeatureTest(生成tests/Feature/ExampleFeatureTest.php,继承Tests\TestCase,加载Laravel环境)。
  • 编写测试方法:测试方法以test_开头或添加@test注解,使用断言验证预期结果。例如:
    • 单元测试(测试纯逻辑,如数学计算):
      namespace Tests\Unit;
      use PHPUnit\Framework\TestCase;
      class ExampleUnitTest extends TestCase {
          public function test_addition() {
              $this->assertEquals(4, 2 + 2); // 断言2+2等于4
          }
      }
      
    • 功能测试(测试HTTP请求、数据库操作):
      namespace Tests\Feature;
      use Illuminate\Foundation\Testing\RefreshDatabase;
      use Tests\TestCase;
      class ExampleFeatureTest extends TestCase {
          use RefreshDatabase; // 每次测试前后自动迁移/重置数据库
          public function test_home_page() {
              $response = $this->get('/'); // 发送GET请求到首页
              $response->assertStatus(200); // 断言状态码为200
          }
          public function test_user_registration() {
              $user = \App\Models\User::factory()->create(); // 使用工厂创建测试用户
              $response = $this->get("/user/{$user->id}"); // 访问用户详情页
              $response->assertSee($user->name); // 断言页面包含用户名
          }
      }
      

5. 运行测试

  • 运行所有测试:在项目根目录下执行./vendor/bin/phpunit(Linux/macOS)或vendor\bin\phpunit(Windows),PHPUnit会自动查找并执行tests/目录下的所有测试用例。
  • 运行特定测试:通过--filter指定测试类或方法,如./vendor/bin/phpunit --filter ExampleUnitTest(运行ExampleUnitTest类)、./vendor/bin/phpunit --filter test_addition(运行test_addition方法)。
  • 测试结果分析:测试通过时显示绿色“OK”;失败时显示红色“FAILURES”,并列出失败的方法及错误信息(如断言不匹配、异常抛出),根据提示定位并修复代码问题。

6. 高级测试(可选)

  • 数据库测试:使用RefreshDatabase trait(use RefreshDatabase;)自动处理数据库迁移和重置,确保每次测试在干净的数据库环境中运行。例如:
    public function test_user_creation() {
        $user = \App\Models\User::factory()->create(['email' => 'test@example.com']);
        $this->assertDatabaseHas('users', ['email' => 'test@example.com']); // 断言数据库中存在该用户
    }
    
  • HTTP请求测试:使用Laravel提供的getpostputdelete等方法模拟HTTP请求,结合assertStatus(断言状态码)、assertSee(断言页面包含内容)、assertRedirect(断言重定向)等断言验证响应。例如:
    public function test_login() {
        $response = $this->post('/login', ['email' => 'user@example.com', 'password' => 'password']);
        $response->assertRedirect('/dashboard'); // 断言登录后重定向到仪表盘
    }
    
  • 自动化测试(CI/CD):将测试集成到持续集成/持续部署流程(如GitHub Actions、GitLab CI/CD),实现代码提交时自动运行测试。以GitHub Actions为例,在项目根目录创建.github/workflows/php.yml文件:
    name: PHP CI
    on: [push, pull_request]
    jobs:
      build:
        runs-on: ubuntu-latest
        services:
          mysql:
            image: mysql:8.0
            env:
              MYSQL_DATABASE: laravel_test
              MYSQL_ROOT_PASSWORD: root
              MYSQL_USER: laravel_user
              MYSQL_PASSWORD: your_password
            ports:
              - 3306:3306
            volumes:
              - db_data:/var/lib/mysql
        steps:
          - uses: actions/checkout@v2
          - name: Set up PHP
            uses: shivammathur/setup-php@v2
            with:
              php-version: '8.2'
          - name: Install dependencies
            run: composer install --no-progress --prefer-dist --optimize-autoloader
          - name: Run tests
            env:
              DB_CONNECTION: mysql
              DB_HOST: 127.0.0.1
              DB_PORT: 3306
              DB_DATABASE: laravel_test
              DB_USERNAME: laravel_user
              DB_PASSWORD: your_password
            run: ./vendor/bin/phpunit
    volumes:
      db_data:
    

0