跳转至内容

模拟对象 (Mocking)

简介

在测试 Laravel 应用程序时,您可能希望“模拟”应用程序的某些部分,以便它们在给定的测试中不会真正执行。例如,在测试一个分发事件的控制器时,您可能希望模拟事件监听器,这样它们就不会在测试期间真正执行。这使您能够仅测试控制器的 HTTP 响应,而无需担心事件监听器的执行,因为事件监听器可以在它们自己的测试用例中进行测试。

Laravel 开箱即用地提供了用于模拟事件、作业和其他门面的实用方法。这些辅助工具主要为 Mockery 提供了一层便捷包装,因此您不必手动编写复杂的 Mockery 方法调用。

模拟对象 (Mocking Objects)

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

1use App\Service;
2use Mockery;
3use Mockery\MockInterface;
4 
5test('something can be mocked', function () {
6 $this->instance(
7 Service::class,
8 Mockery::mock(Service::class, function (MockInterface $mock) {
9 $mock->expects('process');
10 })
11 );
12});
1use App\Service;
2use Mockery;
3use Mockery\MockInterface;
4 
5public function test_something_can_be_mocked(): void
6{
7 $this->instance(
8 Service::class,
9 Mockery::mock(Service::class, function (MockInterface $mock) {
10 $mock->expects('process');
11 })
12 );
13}

为了更方便地实现这一点,您可以使用 Laravel 基础测试类提供的 mock 方法。例如,以下示例与上述示例等效:

1use App\Service;
2use Mockery\MockInterface;
3 
4$mock = $this->mock(Service::class, function (MockInterface $mock) {
5 $mock->expects('process');
6});

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

1use App\Service;
2use Mockery\MockInterface;
3 
4$mock = $this->partialMock(Service::class, function (MockInterface $mock) {
5 $mock->expects('process');
6});

同样,如果您想对某个对象进行 监控 (spy),Laravel 的基础测试类提供了一个 spy 方法,作为对 Mockery::spy 方法的便捷封装。间谍 (Spies) 与模拟 (Mocks) 类似;不过,间谍会记录间谍与被测代码之间的所有交互,从而允许您在代码执行后进行断言。

1use App\Service;
2 
3$spy = $this->spy(Service::class);
4 
5// ...
6 
7$spy->shouldHaveReceived('process');

模拟门面 (Mocking Facades)

与传统的静态方法调用不同,门面 (facades)(包括实时门面)是可以被模拟的。与传统静态方法相比,这提供了巨大的优势,并为您提供了与使用传统依赖注入相同的可测试性。在测试时,您通常需要模拟控制器中调用的 Laravel 门面。例如,考虑以下控制器操作:

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Support\Facades\Cache;
6 
7class UserController extends Controller
8{
9 /**
10 * Retrieve a list of all users of the application.
11 */
12 public function index(): array
13 {
14 $value = Cache::get('key');
15 
16 return [
17 // ...
18 ];
19 }
20}

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

1<?php
2 
3use Illuminate\Support\Facades\Cache;
4 
5test('get index', function () {
6 Cache::expects('get')
7 ->with('key')
8 ->andReturn('value');
9 
10 $response = $this->get('/users');
11 
12 // ...
13});
1<?php
2 
3namespace Tests\Feature;
4 
5use Illuminate\Support\Facades\Cache;
6use Tests\TestCase;
7 
8class UserControllerTest extends TestCase
9{
10 public function test_get_index(): void
11 {
12 Cache::expects('get')
13 ->with('key')
14 ->andReturn('value');
15 
16 $response = $this->get('/users');
17 
18 // ...
19 }
20}

您不应该模拟 Request 门面。相反,在运行测试时,请将所需的输入传递给 HTTP 测试方法(例如 getpost)。同样,与其模拟 Config 门面,不如在测试中调用 Config::set 方法。

门面间谍 (Facade Spies)

如果您想对门面进行 监控 (spy),可以在相应的门面上调用 spy 方法。间谍与模拟类似;不过,间谍会记录间谍与被测代码之间的所有交互,从而允许您在代码执行后进行断言。

1<?php
2 
3use Illuminate\Support\Facades\Cache;
4 
5test('values are stored in cache', function () {
6 Cache::spy();
7 
8 $response = $this->get('/');
9 
10 $response->assertStatus(200);
11 
12 Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10);
13});
1use Illuminate\Support\Facades\Cache;
2 
3public function test_values_are_stored_in_cache(): void
4{
5 Cache::spy();
6 
7 $response = $this->get('/');
8 
9 $response->assertStatus(200);
10 
11 Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10);
12}

时间处理 (Interacting With Time)

在测试时,您偶尔需要修改诸如 nowIlluminate\Support\Carbon::now() 等辅助函数返回的时间。值得庆幸的是,Laravel 的基础功能测试类包含了一些辅助工具,允许您操控当前时间。

1test('time can be manipulated', function () {
2 // Travel into the future...
3 $this->travel(5)->milliseconds();
4 $this->travel(5)->seconds();
5 $this->travel(5)->minutes();
6 $this->travel(5)->hours();
7 $this->travel(5)->days();
8 $this->travel(5)->weeks();
9 $this->travel(5)->years();
10 
11 // Travel into the past...
12 $this->travel(-5)->hours();
13 
14 // Travel to an explicit time...
15 $this->travelTo(now()->minus(hours: 6));
16 
17 // Return back to the present time...
18 $this->travelBack();
19});
1public function test_time_can_be_manipulated(): void
2{
3 // Travel into the future...
4 $this->travel(5)->milliseconds();
5 $this->travel(5)->seconds();
6 $this->travel(5)->minutes();
7 $this->travel(5)->hours();
8 $this->travel(5)->days();
9 $this->travel(5)->weeks();
10 $this->travel(5)->years();
11 
12 // Travel into the past...
13 $this->travel(-5)->hours();
14 
15 // Travel to an explicit time...
16 $this->travelTo(now()->minus(hours: 6));
17 
18 // Return back to the present time...
19 $this->travelBack();
20}

您还可以向各种时间跳转方法提供一个闭包。该闭包将在冻结的时间点被调用。闭包执行完毕后,时间将恢复正常。

1$this->travel(5)->days(function () {
2 // Test something five days into the future...
3});
4 
5$this->travelTo(now()->mins(days: 10), function () {
6 // Test something during a given moment...
7});

freezeTime 方法可用于冻结当前时间。同样,freezeSecond 方法也会冻结当前时间,但会将时间点定在当前秒的起始时刻。

1use Illuminate\Support\Carbon;
2 
3// Freeze time and resume normal time after executing closure...
4$this->freezeTime(function (Carbon $time) {
5 // ...
6});
7 
8// Freeze time at the current second and resume normal time after executing closure...
9$this->freezeSecond(function (Carbon $time) {
10 // ...
11})

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

1use App\Models\Thread;
2 
3test('forum threads lock after one week of inactivity', function () {
4 $thread = Thread::factory()->create();
5 
6 $this->travel(1)->week();
7 
8 expect($thread->isLockedByInactivity())->toBeTrue();
9});
1use App\Models\Thread;
2 
3public function test_forum_threads_lock_after_one_week_of_inactivity()
4{
5 $thread = Thread::factory()->create();
6 
7 $this->travel(1)->week();
8 
9 $this->assertTrue($thread->isLockedByInactivity());
10}