rouxtaccess / laravel-openapi-test
1.4.0
2024-07-01 07:59 UTC
Requires
- php: >=7.4|>=8.0
- ext-json: *
- byjg/swagger-test: ^3.1.1
- darkaonline/l5-swagger: ^8.6
- laravel/framework: *
README
底层逻辑使用来自 byjg 的 PHP Swagger Test,用于与 L5-Swagger 一起使用。这是基于 pionl 的 Laravel Swagger Test 开发的。
使用 Laravel 的底层请求测试来测试您的 API 架构。
支持
有关断言如何针对您的文档进行工作的信息,请查看 PHP Swagger Test。
目前,此工具仅支持 JSON API,覆盖任何所需功能应该非常简单。
安装
-
需要此包
composer require --dev rouxtaccess/laravel-openapi-test
用法
使用 Laravel 的 TestCase 并添加 ImplementsOpenApiFunctions
特性。
将 $this->setUpOpenApiTester();
添加到测试的 setUp 函数中
使用与 ApiRequester
相同的 "请求构建"。有关更多详细信息,请参阅 PHP Swagger Test。
对于验证和测试,有 validateRequest()
、validateRequestFails()
、sendRequest()
、validateResponse(Response::HTTP_OK);
等方法。
要在 OpenApi 所需规范之上断言响应数据,可以使用 assertResponseHas()
辅助方法。下面是示例。
<?php namespace Tests\Feature\Api; use App\User; use RouxtAccess\OpenApi\Testing\Laravel\Traits\ImplementsOpenApiFunctions; use Symfony\Component\HttpFoundation\Response; use Tests\TestCase; class AuthLoginTest extends TestCase { use ImplementsOpenApiFunctions; protected function setUp(): void { parent::setUp(); $this->setUpOpenApiTester(); } public function testLoginWithoutDetails() { $this->requester->withMethod('POST') ->withPath('/api/auth/login'); $this->validateRequestFails() ->sendRequest() ->validateResponse(Response::HTTP_UNPROCESSABLE_ENTITY); $this->assertResponseHas('errors.email'); $this->assertResponseHas('errors.password'); } public function testLoginIncorrectDetails() { $this->requester->withMethod('POST') ->withPath('/api/auth/login') ->withRequestBody(['email' => 'not_a_real_users_email@notreal.com', 'password' => 'not_a_valid_password']); $this->validateRequestFails() ->sendRequest() ->validateResponse(Response::HTTP_UNAUTHORIZED); } public function testLoginSuccess() { $user = factory(User::class)->create(['name' => 'test-user', 'email' => 'testemail@example.com', 'password' => bcrypt('bestpassword')]); $this->requester->withMethod('POST') ->withPath('/api/auth/login') ->withRequestBody(['email' => $user->email, 'password' => 'bestpassword']); $this->validateRequest() ->sendRequest() ->validateResponse(Response::HTTP_OK); } }