Laravel 自帶了兩種測試類型
- Feature Test: 功能測試。針對類似接口這種流程性的測試。
- Unit Test: 單元測試。針對單個函數這種輸入輸出結果的測試。
新建一個 Feature Test
php artisan make:test FinishOrderTest
項目根目錄下多了一個文件
tests/Feature/FinishOrderTest.php
安裝 phpunit
要執行測試案例,就需要安裝 phpunit,否則會報錯
zsh: command not found: phpunit
安裝方法
composer require --dev phpunit/phpunit
注意,最好不要指定版本安裝
[InvalidArgumentException] Package phpunit/phpunit at version ^7 has a PHP requirement incompatible with your PHP version (7.0.18)
執行測試案例
./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), ]; });
