cod*_*ire 2 php phpunit laravel laravel-queue
当工作完成时,我试图抓住一个事件
测试代码:
class MyTest extends TestCase {
public function testJobsEvents ()
{
Queue::after(function (JobProcessed $event) {
// if ( $job is 'MyJob1' ) then do test
dump($event->job->payload());
$event->job->payload()
});
$response = $this->post('/api/user', [ 'test' => 'data' ], $this->headers);
$response->assertSuccessful($response->isOk());
}
}
Run Code Online (Sandbox Code Playgroud)
UserController中的方法:
public function userAction (Request $request) {
MyJob1::dispatch($request->toArray());
MyJob2::dispatch($request->toArray());
return response(null, 200);
}
Run Code Online (Sandbox Code Playgroud)
我的工作:
class Job1 implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $data = [];
public function __construct($data)
{
$this->data= $data;
}
public function handle()
{
// Process uploaded
}
}
Run Code Online (Sandbox Code Playgroud)
我需要检查一些数据的作业完成,但我从串行数据后,
$event->job->payload()
在Queue::after
我不知道如何检查的工作吗?
Bon*_*ian 22
那么,要测试handle
方法内部的逻辑,您只需要实例化作业类并调用该handle
方法.
public function testJobsEvents()
{
$job = new \App\Jobs\YourJob;
$job->handle();
// Assert the side effect of your job...
}
Run Code Online (Sandbox Code Playgroud)
记住,毕竟工作只是一个阶级.
sum*_*eet 14
Laravel 版本 ^5 || ^7
同步调度
如果您想立即(同步)调度作业,您可以使用 dispatchNow 方法。使用此方法时,作业不会排队,会立即在当前进程内运行:
Job::dispatchNow()
Laravel 8 更新
<?php
namespace Tests\Feature;
use App\Jobs\ShipOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Bus;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_orders_can_be_shipped()
{
Bus::fake();
// Perform order shipping...
// Assert that a job was dispatched...
Bus::assertDispatched(ShipOrder::class);
// Assert a job was not dispatched...
Bus::assertNotDispatched(AnotherJob::class);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6997 次 |
最近记录: |