15

当工作完成时,我尝试捕捉一个事件

测试代码:

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());

   }

}

UserController中的方法:

public function userAction (Request $request) {

    MyJob1::dispatch($request->toArray());
    MyJob2::dispatch($request->toArray());
    return response(null, 200);
}

我的工作:

class Job1 implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

     public $data = [];

     public function __construct($data)
     {
         $this->data= $data;
     }

      public function handle()
      {
          // Process uploaded
      }
}

作业完成后我需要检查一些数据,但我从 $event->job->payload()in获取序列化数据Queue::after而且我不明白如何检查作业?

4

2 回答 2

51

好吧,要测试方法内部的逻辑,handle您只需要实例化作业类并调用该handle方法。

public function testJobsEvents()
{
       $job = new \App\Jobs\YourJob;
       $job->handle();

       // Assert the side effect of your job...
}

请记住,工作毕竟只是一门课。

于 2018-04-24T10:49:44.073 回答
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);
    }
}
于 2019-12-11T13:59:02.580 回答