簡體   English   中英

如何測試 Laravel 5 工作?

[英]How to test Laravel 5 jobs?

當工作完成時,我嘗試捕捉一個事件

測試代碼:

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
      }
}

我需要在作業完成后檢查一些數據,但我從Queue::after $event->job->payload()獲得序列化數據而且我不明白如何檢查作業?

好吧,要測試handle方法中的邏輯,您只需要實例化作業類並調用handle方法。

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

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

請記住,工作畢竟只是一個班級。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM