温馨提示×

centos下laravel测试怎么进行

小樊
54
2025-09-30 13:10:29
栏目: 智能运维

CentOS下进行Laravel测试的完整步骤

1. 准备测试环境

在开始测试前,需确保CentOS系统已安装Laravel运行所需的依赖(PHP、Composer、Web服务器、数据库),并完成Laravel项目的基础配置:

  • 安装必要软件包:使用yum安装PHP(含mbstringxmlpdo_mysql等扩展)、Composer、Nginx/Apache、MySQL/MariaDB。
    sudo yum install epel-release
    sudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
    sudo yum-config-manager --enable remi-php74  # 启用PHP 7.4仓库(根据需求调整版本)
    sudo yum install php php-cli php-fpm php-mysqlnd php-mbstring php-xml php-zip composer nginx mariadb-server
    
  • 配置Web服务器:以Nginx为例,创建Laravel项目的server配置(指向public目录),并启动服务:
    sudo vim /etc/nginx/conf.d/laravel.conf
    # 添加以下内容(替换项目路径和域名)
    server {
        listen 80;
        server_name your_domain_or_IP;
        root /var/www/laravel_project/public;
        index index.php index.html;
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
        location ~ \.php$ {
            fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    sudo systemctl start nginx
    sudo systemctl enable nginx
    
  • 部署Laravel项目:使用Composer创建项目,配置.env文件(设置数据库连接、应用密钥):
    composer create-project --prefer-dist laravel/laravel laravel_test
    cd laravel_test
    cp .env.example .env
    nano .env  # 修改数据库配置:DB_DATABASE/USER/PASSWORD
    php artisan key:generate
    php artisan migrate  # 创建数据库表
    

2. 编写测试用例

Laravel的测试文件存放在tests目录下,分为功能测试Feature子目录)和单元测试Unit子目录)。以下是常见测试场景的示例:

基础功能测试(检查路由响应)

tests/Feature/ExampleTest.php中编写测试,验证首页是否能正常访问:

<?php
namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    // 使用RefreshDatabase trait重置数据库状态(避免测试数据污染)
    use RefreshDatabase;

    /** @test */
    public function homepage_returns_200_status()
    {
        $response = $this->get('/');
        $response->assertStatus(200);  // 断言返回200状态码
    }

    /** @test */
    public function about_page_exists()
    {
        $response = $this->get('/about');
        $response->assertSee('About Us');  // 断言页面包含指定文本
    }
}
数据库测试(验证数据操作)

使用RefreshDatabase trait确保每次测试前数据库是干净的,测试用户创建功能:

<?php
namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function user_can_be_created()
    {
        $user = User::factory()->create(['name' => 'Test User', 'email' => 'test@example.com']);
        $this->assertDatabaseHas('users', ['email' => 'test@example.com']);  // 断言数据库存在该用户
    }
}
API测试(验证接口响应)

测试API端点的返回数据格式:

/** @test */
public function api_users_endpoint_returns_json()
{
    $response = $this->getJson('/api/users');
    $response->assertStatus(200)
             ->assertJsonStructure(['data' => [['id', 'name', 'email']]]);
}

3. 运行测试

Laravel提供了两种运行测试的方式,可根据需求选择:

方式一:使用Artisan命令(推荐)
php artisan test

该命令会自动检测tests目录下的所有测试类,并输出详细的测试结果(包括通过/失败的用例、错误信息)。

方式二:使用PHPUnit直接运行
vendor/bin/phpunit

或针对特定测试类/方法:

vendor/bin/phpunit tests/Feature/ExampleTest.php  # 运行指定测试类
vendor/bin/phpunit tests/Feature/ExampleTest.php --filter test_homepage_returns_200_status  # 运行指定方法

4. 高级测试技巧

  • 模拟HTTP请求:使用$this->post()$this->put()等方法模拟表单提交,测试POST/PUT接口。
  • 断言常用方法
    • $response->assertStatus(200):断言状态码。
    • $response->assertSee('text'):断言页面包含指定文本。
    • $response->assertJson(['key' => 'value']):断言JSON响应包含指定键值对。
    • $this->assertDatabaseHas('table', ['column' => 'value']):断言数据库存在符合条件的记录。
  • 测试异常:使用$this->expectException()验证代码是否抛出预期异常。
    /** @test */
    public function invalid_user_creation_throws_exception()
    {
        $this->expectException(\Illuminate\Validation\ValidationException::class);
        User::create([]);  // 缺少必填字段,应抛出异常
    }
    

通过以上步骤,你可以在CentOS环境下完成Laravel项目的功能测试、数据库测试和API测试,确保代码质量与稳定性。

0