简介

在测试 Laravel 应用时,您可能希望“模拟”应用的某些方面,以便在特定测试中不实际执行它们。例如,在测试一个分发事件的控制器时,您可能希望模拟事件监听器,使其在测试期间不被实际执行。这样,您只需测试控制器的 HTTP 响应,而无需担心事件监听器的执行,因为事件监听器可以在其自己的测试用例中进行测试。

Laravel 开箱即用提供了用于模拟事件、作业和其他 Facades 的辅助方法。这些辅助方法主要在 Mockery 之上提供了一个便捷层,因此您无需手动进行复杂的 Mockery 方法调用。

模拟对象

当模拟将通过 Laravel 的 服务容器 注入到您的应用程序中的对象时,您需要将您的模拟实例作为 instance 绑定到容器中。这将指示容器使用您对该对象的模拟实例,而不是自行构造该对象:

use App\Service;
use Mockery;
use Mockery\MockInterface;

test('something can be mocked', function () {
    $this->instance(
        Service::class,
        Mockery::mock(Service::class, function (MockInterface $mock) {
            $mock->expects('process');
        })
    );
});
use App\Service;
use Mockery;
use Mockery\MockInterface;

public function test_something_can_be_mocked(): void
{
    $this->instance(
        Service::class,
        Mockery::mock(Service::class, function (MockInterface $mock) {
            $mock->expects('process');
        })
    );
}

为了更加便捷,您可以使用 Laravel 基础测试类提供的 mock 方法。例如,以下示例与上述示例等价:

use App\Service;
use Mockery\MockInterface;

$mock = $this->mock(Service::class, function (MockInterface $mock) {
    $mock->expects('process');
});

当您只需要模拟对象的少数方法时,可以使用 partialMock 方法。未被模拟的方法在被调用时将正常执行:

use App\Service;
use Mockery\MockInterface;

$mock = $this->partialMock(Service::class, function (MockInterface $mock) {
    $mock->expects('process');
});

同样,如果您想对对象进行 窥探(spy),Laravel 的基础测试类提供了一个 spy 方法,作为 Mockery::spy 方法的便捷封装。窥探器类似于模拟;然而,窥探器会记录窥探器与被测代码之间的任何交互,允许您在代码执行后做出断言:

use App\Service;

$spy = $this->spy(Service::class);

// ...

$spy->shouldHaveReceived('process');

模拟 Facades

与传统静态方法调用不同,Facades(包括 实时 Facades)可以被模拟。这相比传统静态方法具有巨大优势,并赋予您与使用传统依赖注入相同的可测试性。在测试时,您通常可能希望模拟控制器中发生的对 Laravel Facade 的调用。例如,考虑以下控制器动作:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    /**
     * Retrieve a list of all users of the application.
     */
    public function index(): array
    {
        $value = Cache::get('key');

        return [
            // ...
        ];
    }
}

我们可以使用 expects 方法来模拟对 Cache Facade 的调用,该方法将返回一个 Mockery 模拟实例。由于 Facades 实际上是由 Laravel 服务容器 解析和管理的,因此它们比典型的静态类具有更强的可测试性。例如,让我们模拟对 Cache Facade 的 get 方法的调用:

<?php

use Illuminate\Support\Facades\Cache;

test('get index', function () {
    Cache::expects('get')
        ->with('key')
        ->andReturn('value');

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

    // ...
});
<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_get_index(): void
    {
        Cache::expects('get')
            ->with('key')
            ->andReturn('value');

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

        // ...
    }
}

您不应模拟 Request Facade。相反,在运行测试时,将所需的输入传递给 HTTP 测试方法(如 get 和 post)。同样,不要模拟 Config Facade,而是在测试中调用 Config::set 方法。

Facades 窥探器

如果您想要对 facade 进行spy,您可以在对应的 facade 上调用 spy 方法。Spies 与 mocks 类似;然而,spies 会记录 spy 与被测试代码之间的任何交互,允许您在代码执行后进行断言:

<?php

use Illuminate\Support\Facades\Cache;

test('values are stored in cache', function () {
    Cache::spy();

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

    $response->assertStatus(200);

    Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10);
});
use Illuminate\Support\Facades\Cache;

public function test_values_are_stored_in_cache(): void
{
    Cache::spy();

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

    $response->assertStatus(200);

    Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10);
}

与时间交互

在测试时,您可能偶尔需要修改由 now 或 Illuminate\Support\Carbon::now() 等辅助函数返回的时间。幸运的是,Laravel 的基础功能测试类包含了一些允许您操纵当前时间的辅助函数:

test('time can be manipulated', function () {
    // Travel into the future...
    $this->travel(5)->milliseconds();
    $this->travel(5)->seconds();
    $this->travel(5)->minutes();
    $this->travel(5)->hours();
    $this->travel(5)->days();
    $this->travel(5)->weeks();
    $this->travel(5)->years();

    // Travel into the past...
    $this->travel(-5)->hours();

    // Travel to an explicit time...
    $this->travelTo(now()->minus(hours: 6));

    // Return back to the present time...
    $this->travelBack();
});
public function test_time_can_be_manipulated(): void
{
    // Travel into the future...
    $this->travel(5)->milliseconds();
    $this->travel(5)->seconds();
    $this->travel(5)->minutes();
    $this->travel(5)->hours();
    $this->travel(5)->days();
    $this->travel(5)->weeks();
    $this->travel(5)->years();

    // Travel into the past...
    $this->travel(-5)->hours();

    // Travel to an explicit time...
    $this->travelTo(now()->minus(hours: 6));

    // Return back to the present time...
    $this->travelBack();
}

您还可以将闭包提供给各种时间旅行方法。该闭包将在指定的时间被冻结时调用。一旦闭包执行完毕,时间将恢复正常:

$this->travel(5)->days(function () {
    // Test something five days into the future...
});

$this->travelTo(now()->minus(days: 10), function () {
    // Test something during a given moment...
});

freezeTime 方法可用于冻结当前时间。同样,freezeSecond 方法将冻结当前时间,但停留在当前秒的开始:

use Illuminate\Support\Carbon;

// Freeze time and resume normal time after executing closure...
$this->freezeTime(function (Carbon $time) {
    // ...
});

// Freeze time at the current second and resume normal time after executing closure...
$this->freezeSecond(function (Carbon $time) {
    // ...
});

正如您所预期的那样,上述所有方法主要用于测试对时间敏感的应用程序行为,例如锁定讨论论坛中不活跃的帖子:

use App\Models\Thread;

test('forum threads lock after one week of inactivity', function () {
    $thread = Thread::factory()->create();

    $this->travel(1)->week();

    expect($thread->isLockedByInactivity())->toBeTrue();
});
use App\Models\Thread;

public function test_forum_threads_lock_after_one_week_of_inactivity()
{
    $thread = Thread::factory()->create();

    $this->travel(1)->week();

    $this->assertTrue($thread->isLockedByInactivity());
}