测试模拟器

简介

在 Laravel 应用程序测试中,你可能希望「模拟」应用程序的某些功能的行为,从而避免该部分在测试中真正执行。例如:在测试调度事件的控制器时,您可能希望模拟事件侦听器,从而避免该事件在测试控制器时真正执行。这允许你在仅测试控制器 HTTP 响应的情况时,而不必担心触发事件。当然,你也可以在单独的测试中测试该事件逻辑。

Laravel 针对事件、任务和 Facades 的模拟,提供了开箱即用的辅助函数。这些函数基于 Mocker 封装而成,使用非常方便,无需手动调用复杂的 Mockery 函数。当然你也可以使用 Mockery 或者使用 PHPUnit 创建自己的模拟器。

模拟对象

当模拟一个对象将通过 Laravel 的服务容器注入到应用中时,你将需要将模拟实例作为 instance 绑定到容器中。这将告诉容器使用对象的模拟实例,而不是构造对象的真身:

  1. use Mockery;
  2. use App\Service;
  3. $this->instance(Service::class, Mockery::mock(Service::class, function ($mock) {
  4. $mock->shouldReceive('process')->once();
  5. }));

为了让以上过程更加便捷,你可以使用 Laravel 的基本测试用例类提供mock 方法:

  1. use App\Service;
  2. $this->mock(Service::class, function ($mock) {
  3. $mock->shouldReceive('process')->once();
  4. });

任务模拟

作为模拟的替代方式,你可以使用 Bus Facade的 fake 方法来防止任务被真正分发执行。使用 fake 的时候,断言一般出现在测试代码的后面:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Jobs\ShipOrder;
  5. use Illuminate\Support\Facades\Bus;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Bus::fake();
  13. // 执行订单发货...
  14. Bus::assertDispatched(ShipOrder::class, function ($job) use ($order) {
  15. return $job->order->id === $order->id;
  16. });
  17. // 断言任务并未分发...
  18. Bus::assertNotDispatched(AnotherJob::class);
  19. }
  20. }

事件模拟

作为mock的替代方法,你可以使用 Event Facade的 fake 方法来模拟事件监听,测试的时候并不会真正触发事件监听器。然后你就可以测试断言事件运行了,甚至可以检查他们接收的数据。使用 fake 的时候,断言一般出现在测试代码的后面:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Events\OrderShipped;
  5. use App\Events\OrderFailedToShip;
  6. use Illuminate\Support\Facades\Event;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Foundation\Testing\WithoutMiddleware;
  9. class ExampleTest extends TestCase
  10. {
  11. /**
  12. * 测试订单发送
  13. */
  14. public function testOrderShipping()
  15. {
  16. Event::fake();
  17. // 执行订单发送...
  18. Event::assertDispatched(OrderShipped::class, function ($e) use ($order) {
  19. return $e->order->id === $order->id;
  20. });
  21. // 断言一个事件被发送了两次...
  22. Event::assertDispatched(OrderShipped::class, 2);
  23. // 未分配断言事件...
  24. Event::assertNotDispatched(OrderFailedToShip::class);
  25. }
  26. }

注意:调用 Event::fake() 后不会执行事件监听。所以,你基于事件的测试必须使用工厂模型,例如,在模型的 creating 事件中创建 UUID ,你应该调用 Event::fake() 之后 使用工厂模型。

模拟事件的子集

如果你只想为特定的一组事件模拟事件监听器,你可以将它们传递给 fakefakeFor 方法:

  1. /**
  2. * 测试订单流程
  3. */
  4. public function testOrderProcess()
  5. {
  6. Event::fake([
  7. OrderCreated::class,
  8. ]);
  9. $order = factory(Order::class)->create();
  10. Event::assertDispatched(OrderCreated::class);
  11. // 其他事件照常发送...
  12. $order->update([...]);
  13. }

Scoped 事件模拟

如果你只想为部分测试模拟事件监听,则可以使用 fakeFor 方法:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Order;
  4. use Tests\TestCase;
  5. use App\Events\OrderCreated;
  6. use Illuminate\Support\Facades\Event;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Foundation\Testing\WithoutMiddleware;
  9. class ExampleTest extends TestCase
  10. {
  11. /**
  12. * 测试订单流程
  13. */
  14. public function testOrderProcess()
  15. {
  16. $order = Event::fakeFor(function () {
  17. $order = factory(Order::class)->create();
  18. Event::assertDispatched(OrderCreated::class);
  19. return $order;
  20. });
  21. // 事件按正常方式发送,观察者将运行...
  22. $order->update([...]);
  23. }
  24. }

邮件模拟

你可以是用 Mail Facade 的 fake 方法来模拟邮件发送,测试时不会真的发送邮件,然后你可以断言 mailables 发送给了用户,甚至可以检查他们收到的内容。使用 fakes 时,断言一般放在测试代码的后面:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Mail\OrderShipped;
  5. use Illuminate\Support\Facades\Mail;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Mail::fake();
  13. // 断言没有发送任何邮件...
  14. Mail::assertNothingSent();
  15. // 执行订单发送...
  16. Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
  17. return $mail->order->id === $order->id;
  18. });
  19. // 断言一条发送给用户的消息...
  20. Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
  21. return $mail->hasTo($user->email) &&
  22. $mail->hasCc('...') &&
  23. $mail->hasBcc('...');
  24. });
  25. // 断言邮件被发送两次...
  26. Mail::assertSent(OrderShipped::class, 2);
  27. // 断言没有发送邮件...
  28. Mail::assertNotSent(AnotherMailable::class);
  29. }
  30. }

如果你用后台任务执行邮件发送队列,你应该是用 assertQueued 代替 assertSent

  1. Mail::assertQueued(...);
  2. Mail::assertNotQueued(...);

通知模拟

你可以使用 Notification Facade 的 fake 方法来模拟通知的发送,测试时并不会真的发出通知。然后你可以断言 notifications 发送给了用户,甚至可以检查他们收到的内容。使用 fakes 时,断言一般放在测试代码后面:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Notifications\OrderShipped;
  5. use Illuminate\Support\Facades\Notification;
  6. use Illuminate\Notifications\AnonymousNotifiable;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Foundation\Testing\WithoutMiddleware;
  9. class ExampleTest extends TestCase
  10. {
  11. public function testOrderShipping()
  12. {
  13. Notification::fake();
  14. // 断言没有发送通知...
  15. Notification::assertNothingSent();
  16. // 执行订单发送...
  17. Notification::assertSentTo(
  18. $user,
  19. OrderShipped::class,
  20. function ($notification, $channels) use ($order) {
  21. return $notification->order->id === $order->id;
  22. }
  23. );
  24. // 断言向给定用户发送了通知...
  25. Notification::assertSentTo(
  26. [$user], OrderShipped::class
  27. );
  28. // 断言没有发送通知...
  29. Notification::assertNotSentTo(
  30. [$user], AnotherNotification::class
  31. );
  32. // 断言通过 Notification::route() 方法发送通知...
  33. Notification::assertSentTo(
  34. new AnonymousNotifiable, OrderShipped::class
  35. );
  36. }
  37. }

队列模拟

作为模拟替代方案,你可以使用 Queue Facade 的 fake 方法避免把任务真的放到队列中执行。然后你就可以断言任务已经被推送入队列了,甚至可以检查它们收到的数据。使用 fakes 时,断言一般放在测试代码的后面:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Jobs\ShipOrder;
  5. use Illuminate\Support\Facades\Queue;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Queue::fake();
  13. // 断言没有任务被发送...
  14. Queue::assertNothingPushed();
  15. // 执行订单发送...
  16. Queue::assertPushed(ShipOrder::class, function ($job) use ($order) {
  17. return $job->order->id === $order->id;
  18. });
  19. // 断言任务进入了指定队列...
  20. Queue::assertPushedOn('queue-name', ShipOrder::class);
  21. // 断言任务进入2次...
  22. Queue::assertPushed(ShipOrder::class, 2);
  23. // 断言没有一个任务进入队列...
  24. Queue::assertNotPushed(AnotherJob::class);
  25. // 断言任务是由特定的通道发送的...
  26. Queue::assertPushedWithChain(ShipOrder::class, [
  27. AnotherJob::class,
  28. FinalJob::class
  29. ]);
  30. }
  31. }

存储模拟

你可以使用 Storage Facade 的 fake 方法,轻松的生成一个模拟磁盘,结合 UploadedFile 类的文件生成工具,极大的简化了文件上传测试。例如:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use Illuminate\Http\UploadedFile;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testAvatarUpload()
  11. {
  12. Storage::fake('avatars');
  13. $response = $this->json('POST', '/avatar', [
  14. 'avatar' => UploadedFile::fake()->image('avatar.jpg')
  15. ]);
  16. // 断言文件已存储...
  17. Storage::disk('avatars')->assertExists('avatar.jpg');
  18. // 断言文件不存在...
  19. Storage::disk('avatars')->assertMissing('missing.jpg');
  20. }
  21. }

Tip: 默认情况下,fake 方法将删除临时目录下所有文件。如果你想保留这些文件,你可以使用 「persistentFake」。

Facades

与传统静态方法调用不同的是, facades 也可以被模拟。相较传统的静态方法而言,它具有很大的优势,即便你使用依赖注入,可测试性不逊半分。在测试中,你可能想在控制器中模拟对 Laravel Facade 的调用。比如下面控制器中的行为:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\Cache;
  4. class UserController extends Controller
  5. {
  6. /**
  7. * 显示应用里所有用户
  8. *
  9. * @return Response
  10. */
  11. public function index()
  12. {
  13. $value = Cache::get('key');
  14. //
  15. }
  16. }

我们可以通过 shouldReceive 方法来模拟 Cache Facade,此函数会返回一个 Mockery 实例。由于 Facade 的调用实际是由 Laravel 的 服务容器 管理的,所以 Facade 能比传统的静态类表现出更好的可测试性。下面,让我们模拟一下 Cache Facade 的 get 方法:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. use Illuminate\Foundation\Testing\WithoutMiddleware;
  7. class UserControllerTest extends TestCase
  8. {
  9. public function testGetIndex()
  10. {
  11. Cache::shouldReceive('get')
  12. ->once()
  13. ->with('key')
  14. ->andReturn('value');
  15. $response = $this->get('/users');
  16. // ...
  17. }
  18. }

注意:你不能模拟 Request Facade 。相反,在运行测试时如果需要传入指定参数,请使用 HTTP 辅助函数,比如 getpost 。同理,请在测试时通过调用 Config::set 来模拟 Config Facade。

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

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