Mocking
介绍
在测试 Laravel 应用程序时,您可能希望“模拟”应用程序的某些方面,这样它们在给定的测试中就不会真正执行。例如,在测试一个调度事件的控制器时,您可能希望模拟事件监听器,这样它们在测试期间就不会真正执行。这样您就可以只测试控制器的 HTTP 响应,而不必担心事件监听器的执行,因为事件监听器可以在其自己的测试用例中进行测试。
Laravel 提供了一些实用的方法来模拟事件、任务和其他 Facade。这些辅助方法主要在 Mockery 之上提供了一个便捷的层,让您无需手动进行复杂的 Mockery 方法调用。
模拟对象
当模拟一个即将通过 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}
为了更方便,你可以使用mock
Laravel 基类测试用例提供的方法。例如,下面的示例与上面的例子等效:
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});
类似地,如果你想监视某个对象,Laravel 的基础测试用例类提供了一个spy
方法,可以方便地包装该Mockery::spy
方法。间谍类似于模拟;然而,间谍会记录间谍与被测代码之间的任何交互,从而允许你在代码执行后进行断言:
1use App\Service;2 3$spy = $this->spy(Service::class);4 5// ...6 7$spy->shouldHaveReceived('process');
模拟 Facade
与传统的静态方法调用不同,Facades(包括实时 Facades)可以被模拟。这比传统的静态方法有很大优势,并且赋予您与使用传统依赖注入时相同的可测试性。测试时,您可能经常需要模拟某个控制器中对 Laravel Facade 的调用。例如,考虑以下控制器操作:
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(): array13 {14 $value = Cache::get('key');15 16 return [17 // ...18 ];19 }20}
Cache
我们可以使用 方法来模拟对 Facade 的调用,该方法将返回一个Mockeryexpects
模拟实例。由于 Facade 实际上是由 Laravel服务容器解析和管理的,因此它们比典型的静态类具有更高的可测试性。例如,让我们模拟对Facade方法的调用: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(): void11 {12 Cache::expects('get')13 ->with('key')14 ->andReturn('value');15 16 $response = $this->get('/users');17 18 // ...19 }20}
您不应该模拟Request
Facade。相反,在运行测试时,将所需的输入传递给HTTP 测试方法(例如get
和 )post
。同样,不要模拟Config
Facade,而是Config::set
在测试中调用该方法。
外观间谍
如果您想监视某个外观,可以调用spy
相应外观上的方法。间谍类似于模拟;但是,间谍会记录间谍与被测代码之间的任何交互,从而允许您在代码执行后进行断言:
1<?php 2 3use Illuminate\Support\Facades\Cache; 4 5test('values are be 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_be_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}
与时间互动
now
测试时,你可能偶尔需要修改辅助函数(例如或 )返回的时间Illuminate\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()->subHours(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()->subHours(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()->subDays(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})
正如您所期望的,上面讨论的所有方法主要用于测试时间敏感的应用程序行为,例如锁定讨论论坛上的非Events帖子:
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}