Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PestPHP/Pest -单元测试 #868

Open
guanhui07 opened this issue Dec 17, 2024 · 0 comments
Open

PestPHP/Pest -单元测试 #868

guanhui07 opened this issue Dec 17, 2024 · 0 comments

Comments

@guanhui07
Copy link
Owner

熟悉php的都知道 phpunit/phpunit 可能不知道 pestphp/pest

PestPHP/Pest是一个现代化的 PHP 测试框架,它提供了简洁、优雅的语法来编写 PHPUnit 测试用例,让测试变得更加轻松和高效。

PestPHP/Pest:采用了更简洁、流畅的函数式编程风格,使用test、describe、expect等函数来定义测试用例和断言,代码看起来更清晰易读,具有很强的表达力,让开发者能够以一种更自然的方式编写测试。

composer require pestphp/pest --dev

编写测试用例

基本测试结构:在tests目录下创建测试文件,例如ExampleTest.php。每个测试文件通常以test开头,然后是测试的类名,该类继承自Tests\TestCase。

<?php

use Tests\TestCase;

test('addition works correctly', function () {
    $result = 2 + 3;
    expect($result)->toBe(5);
});

测试方法和断言:

在测试类中,可以定义多个测试方法,每个方法对应一个具体的测试场景。使用expect函数进行断言,用于验证代码的实际输出与预期输出是否一致。

test('string concatenation works', function () {
    $str1 = 'Hello';
    $str2 = ' World';
    $result = $str1. $str2;
    expect($result)->toBe('Hello World');
});

运行测试

vendor/bin/pest


测试数据库操作:

Pest提供了方便的方法来测试数据库相关的代码。可以使用beforeEach和afterEach等钩子函数来设置和清理测试数据。

use Illuminate\Support\Facades\DB;

describe('Database Operations', function () {
    beforeEach(function () {
        // 在每个测试之前插入测试数据
        DB::table('users')->insert([
            'name' => 'John Doe',
            'email' => '[email protected]',
        ]);
    });

    afterEach(function () {
        // 在每个测试之后删除测试数据
        DB::table('users')->where('name', 'John Doe')->delete();
    });

    test('can retrieve user from database', function () {
        $user = DB::table('users')->where('name', 'John Doe')->first();
        expect($user)->not->toBeNull();
        expect($user->name)->toBe('John Doe');
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant