本书未发布
队列任务
就像上一节中的邮件门面一样,在包中实现任务与在Laravel应用程序中完成的工作流程非常相似。
创建一个任务
首先,在包的 src/
目录中创建一个新的 Jobs
目录,并添加一个 PublishPost.php
文件,该文件将负责更新 Post
的 published_at
时间戳。以下是 handle()
方法的示例:
<?php
namespace JohnDoe\BlogPackage\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use JohnDoe\BlogPackage\Models\Post;
class PublishPost implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $post;
public function __construct(Post $post)
{
$this->post = $post;
}
public function handle()
{
$this->post->publish();
}
}
测试调度作业
在本示例,我们在已经测试过的Post
模型上有一个publish()
方法(Post
的单元测试)。我们可以通过在 tests/unit
目录中添加新的 PublishPostTest.php
单元测试来轻松测试预期的行为。
在此测试中,我们可以利用 Bus
门面 提供的一个 fake()
辅助函数来模拟一个真实的实现。调度任务之后,我们可以在 Bus
门面上断言我们的Job已调度并且包含正确的 Post
。
<?php
namespace JohnDoe\BlogPackage\Tests\Unit;
use Illuminate\Support\Facades\Bus;
use JohnDoe\BlogPackage\Jobs\PublishPost;
use JohnDoe\BlogPackage\Models\Post;
use JohnDoe\BlogPackage\Tests\TestCase;
class PublishPostTest extends TestCase
{
/** @test */
public function it_publishes_a_post()
{
Bus::fake();
$post = factory(Post::class)->create();
$this->assertNull($post->published_at);
PublishPost::dispatch($post);
Bus::assertDispatched(PublishPost::class, function ($job) use ($post) {
return $job->post->id === $post->id;
});
}
}
随着测试的通过,您可以在包中安全地使用此任务。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: