沃梦达 / 编程问答 / php问题 / 正文

如何测试 Laravel 5 作业?

How to test Laravel 5 jobs?(如何测试 Laravel 5 作业?)

本文介绍了如何测试 Laravel 5 作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to catch an event, when job is completed

测试代码:

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 而且我不明白如何检查作业?

I need to check some data after job is complete but I get serialized data from $event->job->payload() in Queue::after And I don't understand how to check job ?

推荐答案

好吧,要测试 handle 方法中的逻辑,你只需要实例化作业类 &调用 handle 方法.

Well, to test the logic inside handle method you just need to instantiate the job class & invoke the handle method.

public function testJobsEvents()
{
       $job = new AppJobsYourJob;
       $job->handle();

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

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

Remember, a job is just a class after all.

这篇关于如何测试 Laravel 5 作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何测试 Laravel 5 作业?