iT邦幫忙

2022 iThome 鐵人賽

DAY 5
2
Modern Web

Laravel 9 漫遊,享受魔法般的極速網頁開發體驗系列 第 5

Day 05:魔法般的建立自動化測試,想好函數名稱反而最難?

  • 分享至 

  • xImage
  •  

上次看過 Laravel 9 提供我們的自動化測試內容,今天我們來談怎麼建立自己的自動化測試!

這次測試的內容為

  • 如果連線 hello-world/,HTTP Status 應該要顯示 200(成功連線)
  • 連線到網頁內,應該要可以看到「Hello world!」這些字

跟 Laravel 6 時一樣,我們可以利用 artisan 這個指令列工具,來協助我們建立測試內容

至於怎麼呼叫容器內的 artisan 呢?相信讀者們已經猜到解答了:用 Laravel Sail!

./vendor/bin/sail artisan make:test HelloWorldTest

這樣就建立好囉!

我們來看看這次產出的內容

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class HelloWorldTest extends TestCase
{
    public function test_example()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

細心的讀者或許看出來了,跟 Laravel 6 相比差不多,不過函數的名稱變成以底線區隔,不再是大小寫區隔。

我們先來處理程式最難的問題:給函數一個用意清晰的名字。就稱呼這兩個函數為

  • 如果連線 hello-world/,HTTP Status 應該要顯示 200(成功連線)
    • test_the_hello_world_route_returns_a_successful_response
  • 連線到網頁內,應該要可以看到「Hello world!」這些字
    • test_the_hello_world_route_response_have_hello_world

確定好函數的名字之後,我們就可以寫測試的內容了

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class HelloWorldTest extends TestCase
{
    public function test_the_hello_world_route_returns_a_successful_response()
    {
        $response = $this->get('/hello-world');

        $response->assertStatus(200);
    }
    
    public function test_the_hello_world_route_response_have_hello_world()
    {
        $response = $this->get('/hello-world');

        $response->assertSee('Hello World!');
    }
}

寫好之後,我們就可以快速地進行測試了

$ ./vendor/bin/sail test

   PASS  Tests\Unit\ExampleTest
  ✓ that true is true

   PASS  Tests\Feature\ExampleTest
  ✓ the application returns a successful response

   PASS  Tests\Feature\HelloWorldTest
  ✓ the hello world route returns a successful response
  ✓ the hello world route response have hello world

是不是比起之前還要簡單呢!而且利用明確的函數名稱,我們確實做到讓測試結果非常容易讓人閱讀,甚至連註解都不需要撰寫!

今天有關自動化測試的分享就到這邊,我們明天見!


上一篇
Day 04:基本的測試教學!怎麼用 Laravel Sail 運作自動化測試
下一篇
Day 06:優化我們的網頁外觀,善用 component 減少撰寫的前端程式
系列文
Laravel 9 漫遊,享受魔法般的極速網頁開發體驗30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
json_liang
iT邦研究生 5 級 ‧ 2022-09-05 22:48:01

感謝分享實用技巧

0
太太
iT邦新手 5 級 ‧ 2022-09-13 14:57:04

LGTM

在 PSR-1 裡頭規範 method 需要是小駝峰,
但套用在測試命名需要用一段話來表達測試項目時,確實會增添閱讀上困擾。
(至少一直以來困擾著我XD)

Method names MUST be declared in camelCase().

後來有找到這篇算是替 php unitTest 撰寫風格上的這現象擔當起吹哨者吧XD
https://matthiasnoback.nl/2020/06/unit-test-naming-conventions/

小克 iT邦新手 4 級 ‧ 2022-09-14 12:11:47 檢舉

用 snake_case 來命名測試是 Laravel 的慣例
但是確實對於套用品質管理工具(PHPStan、PHP CS Fixer等)來說十分麻煩...

目前我的做法也只能寫規則排除測試情境了

我要留言

立即登入留言