在测试 Laravel 应用程序时,你可能希望“模拟”应用程序的某些方面,以便它们在给定测试期间不会实际执行。例如,在测试一个分发事件的控制器时,你可能希望模拟事件监听器,以便它们在测试期间不会实际执行。这使你能够只测试控制器的 HTTP 响应而无需担心事件监听器的执行,因为事件监听器可以在它们自己的测试用例中进行测试。
Laravel 提供有用的方法,用于开箱即用地模拟事件、任务和其他门面。这些辅助方法主要在 Mockery 之上提供一个便利层,这样您就不必手动进行复杂的 Mockery 方法调用。
当模拟一个将通过 Laravel 的 服务容器 注入到你的应用中的对象时,你需要将你模拟的实例绑定到容器中,作为 实例 绑定。这将指示容器使用你模拟的对象实例,而不是自行构建该对象:
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');
})
);
}为了让这更方便,你可以使用 mock 方法,该方法由 Laravel 的基础测试用例类提供。例如,下面的示例与上面的示例等效:
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');
});同样, 如果你想监视一个对象, Laravel 的基础测试用例类提供了一个spy方法作为Mockery::spy方法的便捷包装. 监视器类似于模拟对象; 然而, 监视器会记录监视器与被测试代码之间的任何交互, 允许你在代码执行后进行断言:
use App\Service;
$spy = $this->spy(Service::class);
// ...
$spy->shouldHaveReceived('process');与传统静态方法调用不同,门面 (包括 实时门面) 可以被模拟。这相对于传统静态方法提供了一个巨大的优势,并赋予你与使用传统依赖注入时相同的可测试性。在测试时,你可能经常希望模拟对 Laravel 门面的调用,该调用发生在你的一个控制器中。例如,考虑以下控制器操作:
<?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 [
// ...
];
}
}我们可以模拟对 Cache facade 的调用,通过使用 expects 方法,它将返回一个 Mockery 模拟实例。由于 facade 实际上是由 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门面。相反,将你想要的输入传入 HTTP 测试方法,例如get和post,当你运行测试时。同样地,与其模拟Config门面,不如在你的测试中调用Config::set方法。
如果你想 侦测 一个 facade,你可以调用对应 facade 上的 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()->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());
}