模拟
简介
测试 Laravel 应用时,你可能希望「模拟」应用的某些部分,使其在给定测试中不会真正执行。例如,测试会派发事件的控制器时,你可能希望模拟事件监听器,使其在测试期间不真正执行。这样你只需测试控制器的 HTTP 响应,而不必担心事件监听器的执行——因为事件监听器可在自己的测试用例中单独测试。
Laravel 开箱即用提供了用于模拟事件、任务及其他 facade 的实用方法。这些辅助方法主要是在 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->shouldReceive('process')->once();
})
);
});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->shouldReceive('process')->once();
})
);
}为更方便起见,你可以使用 Laravel 基础测试用例类提供的 mock 方法。例如,下面的示例与上面的示例等价:
use App\Service;
use Mockery\MockInterface;
$mock = $this->mock(Service::class, function (MockInterface $mock) {
$mock->shouldReceive('process')->once();
});
若只需模拟对象的少数方法,可使用 partialMock 方法。未被模拟的方法在调用时会正常执行:
use App\Service;
use Mockery\MockInterface;
$mock = $this->partialMock(Service::class, function (MockInterface $mock) {
$mock->shouldReceive('process')->once();
});
同样,若要对对象进行 spy,Laravel 基础测试用例类提供了 spy 方法,作为 Mockery::spy 的便捷封装。Spy 与 mock 类似;不过 spy 会记录与被测代码之间的任何交互,使你能在代码执行后再做断言:
use App\Service;
$spy = $this->spy(Service::class);
// ...
$spy->shouldHaveReceived('process');
模拟 Facade
与传统静态方法调用不同,facade(包括实时 facade)可以被模拟。这相对传统静态方法是一大优势,并赋予你与传统依赖注入相同的可测试性。测试时,你常常希望模拟控制器中对 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 mock 实例。由于 facade 实际上由 Laravel 服务容器解析与管理,其可测试性远高于典型的静态类。例如,我们来模拟对 Cache facade 的 get 方法的调用:
<?php
use Illuminate\Support\Facades\Cache;
test('get index', function () {
Cache::shouldReceive('get')
->once()
->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::shouldReceive('get')
->once()
->with('key')
->andReturn('value');
$response = $this->get('/users');
// ...
}
}WARNING
不应模拟 Request facade。相反,在运行测试时应将所需输入传入 HTTP 测试方法,例如 get 与 post。同样,不要模拟 Config facade,而应在测试中调用 Config::set 方法。
Facade Spy
若要对 facade 进行 spy,可在相应 facade 上调用 spy 方法。Spy 与 mock 类似;不过 spy 会记录与被测代码之间的任何交互,使你能在代码执行后再做断言:
<?php
use Illuminate\Support\Facades\Cache;
test('values are be stored in cache', function () {
Cache::spy();
$response = $this->get('/');
$response->assertStatus(200);
Cache::shouldHaveReceived('put')->once()->with('name', 'Taylor', 10);
});use Illuminate\Support\Facades\Cache;
public function test_values_are_be_stored_in_cache(): void
{
Cache::spy();
$response = $this->get('/');
$response->assertStatus(200);
Cache::shouldHaveReceived('put')->once()->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()->subHours(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()->subHours(6));
// Return back to the present time...
$this->travelBack();
}你也可以向各种时间旅行方法提供闭包。闭包会在时间冻结于指定时刻时被调用。闭包执行完毕后,时间将恢复正常:
$this->travel(5)->days(function () {
// Test something five days into the future...
});
$this->travelTo(now()->subDays(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());
}