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

转载于:https://www.cnblogs.com/sgm4231/p/10195121.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值