对 Laravel 的 Controller 做 Unit Test

发布时间: 2018-09-10 15:46:14 作者: 大象笔记

之前尝试过对 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)
我是一名山东烟台的开发者,联系作者