Laravel 的 JSON API 接口自動化測試

Laravel 自帶了兩種測試類型

  • Feature Test: 功能測試。針對相似接口這種流程性的測試。
  • Unit Test: 單元測試。針對單個函數這種輸入輸出結果的測試。

新建一個 Feature Test

php artisan make:test FinishOrderTest

項目根目錄下多了一個文件php

tests/Feature/FinishOrderTest.phplaravel

安裝 phpunit

要執行測試案例,就須要安裝 phpunit,不然會報錯json

zsh: command not found: phpunitapi

安裝方法composer

composer require --dev phpunit/phpunit

注意,最好不要指定版本安裝dom

[InvalidArgumentException] Package phpunit/phpunit at version ^7 has a PHP requirement incompatible with your PHP version (7.0.18)函數

執行測試案例post

./vendor/bin/phpunit

一個訂單相關的測試案例

cat tests/Feature/FinishOrderTest.php <?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; use App\User; use App\Models\Order; class FinishOrderTest extends TestCase { // use RefreshDatabase; public function testFinishOrderAPI() { $user = factory(User::class)->create(['email' => 'user4@test.com']); $token = $user->createToken('token', [])->accessToken; $headers = ['Authorization' => "Bearer $token"]; $order = Order::orderBy("id", "desc")->first(); $this->json('post', '/api/finish_order', ["order_id" => $order->order_id,], $headers) ->assertStatus(200); } }

測試數據重置

對於沒有使用 migraton 的項目,不要做死使用單元測試

use RefreshDatabase;

他的重置原理是從新運行 migrate, 刪除全部數據表,而後執行 migrate 重建。。。測試

在沒有 migration 文件的狀況下,這就是做死。。。

爲什麼要使用 factory

參考: https://laravel-news.com/learn-to-use-model-factories-in-laravel-5-1

能夠同時使用在 seed 和 test case 中。用於自動生成僞造數據,例如 name, email 等。

參考代碼

cat database/factories/UserFactory.php <?php use Faker\Generator as Faker; $factory->define(App\User::class, function (Faker $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; });
相關文章
相關標籤/搜索