如何测试Laravel 5工作?

2022-08-30 23:53:32

我尝试在作业完成时捕获事件

测试代码:

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

   }

}

用户控制器中的方法:

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()Queue::after


答案 1

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

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

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

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


答案 2

拉拉维尔版本^5 ||^7

同步调度

如果要立即(同步)调度作业,可以使用 dispatchNow 方法。使用此方法时,作业将不会排队,并将在当前进程中立即运行:

Job::dispatchNow()

拉拉维尔 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);
    }
}

推荐