Laravel 8 Facades

2021-07-26 09:36 更新

與傳統(tǒng)靜態(tài)方法調(diào)用不同的是,facades 也可以被模擬。相較傳統(tǒng)的靜態(tài)方法而言,它具有很大的優(yōu)勢(shì),即便你使用依賴注入,可測(cè)試性不遜半分。在測(cè)試中,你可能想在控制器中模擬對(duì) Laravel Facade 的調(diào)用。比如下面控制器中的行為:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    /**
     * 顯示該應(yīng)用程序的所有用戶的列表.
     *
     * @return Response
     */
    public function index()
    {
        $value = Cache::get('key');

        //
    }
} 

我們可以通過(guò) shouldReceive 方法來(lái)模擬 Cache Facade,此函數(shù)會(huì)返回一個(gè) Mockery 實(shí)例。由于 Facade 的調(diào)用實(shí)際是由 Laravel 的 服務(wù)容器 管理的,所以 Facade 能比傳統(tǒng)的靜態(tài)類表現(xiàn)出更好的可測(cè)試性。下面,讓我們模擬一下 Cache Facade 的 get 方法:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function testGetIndex()
    {
        Cache::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');

        $response = $this->get('/users');

        // ...
    }
} 

注意:你不能模擬 Request Facade 。相反,在運(yùn)行測(cè)試時(shí)如果需要傳入指定參數(shù),請(qǐng)使用 HTTP 輔助函數(shù),比如 getpost 。同理,請(qǐng)?jiān)跍y(cè)試時(shí)通過(guò)調(diào)用 Config::set 來(lái)模擬 Config Facade。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)