测试模拟器

未匹配的标注
本文档最新版为 12.x,旧版本可能放弃维护,推荐阅读最新版!

测试模拟器

简介

测试 Laravel 应用时,你可能希望「模拟(mock)」应用的某些部分,使其在特定测试中不被实际执行。例如,测试一个会分发事件的控制器时,你可能希望模拟事件监听器,避免它们在测试中真正运行。这样,你就可以专注于测试控制器的 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->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');

模拟 Facade

你可以模拟 Facade(包括 实时 Facade),这是它相较于传统静态方法调用的一大优势,让你获得与传统依赖注入相同的可测试性。测试时,你可能经常需要模拟控制器中对某个 Laravel Facade 的调用。例如,考虑以下控制器方法:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    /**
     * 获取应用中所有用户的列表。
     */
    public function index(): array
    {
        $value = Cache::get('key');

        return [
            // ...
        ];
    }
}

我们可以使用 expects 方法模拟对 Cache Facade 的调用,该方法会返回一个 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');

        // ...
    }
}

[!WARNING]
你不应模拟 Request Facade。运行测试时,应将所需的输入传给 get、post 等 HTTP 测试方法。同样,也不应模拟 Config Facade,而应在测试中调用 Config::set 方法。

Facade 监视器

如果你想 监视(spy) 某个 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 () {
    // 前往未来……
    $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();

    // 回到过去……
    $this->travel(-5)->hours();

    // 前往指定时刻……
    $this->travelTo(now()->minus(hours: 6));

    // 返回当前时间……
    $this->travelBack();
});
public function test_time_can_be_manipulated(): void
{
    // 前往未来……
    $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();

    // 回到过去……
    $this->travel(-5)->hours();

    // 前往指定时刻……
    $this->travelTo(now()->minus(hours: 6));

    // 返回当前时间……
    $this->travelBack();
}

你也可以向各种时间旅行方法传入闭包。闭包执行期间,时间会冻结在指定时刻。闭包执行完毕后,时间将恢复正常:

$this->travel(5)->days(function () {
    // 测试五天后的某项行为……
});

$this->travelTo(now()->minus(days: 10), function () {
    // 测试指定时刻的某项行为……
});

freezeTime 方法可以冻结当前时间。类似地,freezeSecond 方法会将时间冻结在当前秒的起始处:

use Illuminate\Support\Carbon;

// 冻结时间,执行闭包后恢复正常时间……
$this->freezeTime(function (Carbon $time) {
    // ...
});

// 将时间冻结在当前秒的起始处,执行闭包后恢复正常时间……
$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());
}

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/laravel/13.x/mo...

译文地址:https://learnku.com/docs/laravel/13.x/mo...

上一篇 下一篇
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~