aurhurian/laravel-test-generator

为 Laravel 模型、控制器和请求生成测试的包。

1.0.2.0 2024-03-23 17:54 UTC

This package is auto-updated.

Last update: 2024-09-23 19:06:06 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

Laravel Test Generator

使用此包为您的 Laravel 应用程序生成测试文件,并在之后修复测试。

请注意

此包仍在开发中,可能无法按预期工作。请自行承担风险。

生成的测试结果并不完整。您应填写此测试的逻辑。

安装

使用 composer 安装此包。

composer require aunhurian/laravel-test-generator

用法

php artisan test:generate "\App\Http\Controllers\IndexController" --feature --unit

您可以使用 override 选项覆盖现有的测试文件。

php artisan test:generate "\App\Http\Controllers\IndexController" --feature --unit --override

您还可以使用以下命令发布配置文件

php artisan vendor:publish --tag=test-generator --force

为测试生成器创建自己的格式化器,并在配置 test-generator 中设置该类。您需要实现 AUnhurian\LaravelTestGenerator\Contracts\FormatorInterface 接口。

示例

您有一个控制器 IndexController,具有以下方法

class IndexController extends Controller
{
    public function __construct(private string $test = '')
    {
    }

    public function test(Request $request, int $id)
    {
        return view('welcome', [
            'data' => $request->all()
        ]);
    }

    public function show(): JsonResponse
    {
        return response()->json([
            'message' => 'success'
        ]);
    }
}

您可以使用以下命令为控制器生成测试文件

php artisan test:generate "\App\Http\Controllers\IndexController" --feature --unit

这将生成以下测试文件

功能测试

它将为控制器生成一个功能测试文件。

<?php

namespace Tests\Feature\Http\Controllers;

use Symfony\Component\HttpFoundation\Response as SymphonyResponse;
use Tests\TestCase;

class IndexControllerTest extends TestCase
{
    public function testTest(): void
    {
        $url = route('test');
        
        $this->get($url)
            ->assertStatus(SymphonyResponse::HTTP_OK);
        
        $this->assertTrue(true);
    }

    public function testShow(): void
    {
        $data = [];
        
        $url = route('testing.test.show', [ 'id' => '',]);
        
        $this->postJson($url, $data)
            ->assertStatus(SymphonyResponse::HTTP_OK)
            ->assertJson([
                //TODO: Add your expected response here
            ]);
        
        $this->assertTrue(true);
    }

}

单元测试

它还将为控制器生成一个单元测试文件。

<?php

namespace Tests\Unit\Http\Controllers;

use App\Http\Controllers\IndexController;
use Illuminate\Http\Request;
use Tests\TestCase;

class IndexControllerTest extends TestCase
{
    public function testTest(): void
    {
        $test = '';
        $request = $this->mock(Request::class);
        $id = '';
        $IndexController = new IndexController($test);
        
        $IndexController->test($request, $id);
        
        $this->assertTrue(true);
    }

    public function testShow(): void
    {
        $test = '';
        $IndexController = new IndexController($test);
        
        $response = $IndexController->show();
        $this->assertNotEmpty($response);
        
        $this->assertTrue(true);
    }

}