1. 程式人生 > >對 Laravel 的 Controller 做 Unit Test

對 Laravel 的 Controller 做 Unit Test

之前嘗試過對 Laravel 的 Controller 做 Feature Test,但是在業務變得越來越複雜之後,我感覺對 controller 裡的函式也沒了自信,急需對功能函式做 Unit Test,以平復我不安的情緒。

例如:

新建一個 Unit Test,由於預設新建的是 feature test, 所有後面需要加上 unit 引數

php artisan make:test StaffSalaryHistoryTest --unit

此時會看到 tests/Unit 目錄下多了一個檔案

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        tests/Unit/StaffSalaryHistoryTest.php

測試程式碼

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Http\Controllers\Admin\StaffSalaryHistoryCrudController;

class StaffSalaryHistoryTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function test_get_start_date_by_last_end_month()
    {
        $controller = new StaffSalaryHistoryCrudController();
        $result = $controller->get_start_date_by_last_end_month('2018-07');
        $this->assertEquals('2018-08-01', $result->format('Y-m-d'));
    }
}

執行測試

 ./vendor/bin/phpunit
PHPUnit 6.5.12 by Sebastian Bergmann and contributors.

...                                                                 3 / 3 (100%)

Time: 961 ms, Memory: 16.00MB

OK (3 tests, 3 assertions)