对 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)
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式