如何测试 Laravel 5 工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46837202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test Laravel 5 jobs?
提问by coder fire
I try to catch an event, when job is completed
当工作完成时,我尝试捕捉一个事件
Test code:
测试代码:
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());
}
}
method in UserController:
UserController 中的方法:
public function userAction (Request $request) {
MyJob1::dispatch($request->toArray());
MyJob2::dispatch($request->toArray());
return response(null, 200);
}
My job:
我的工作:
class Job1 implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $data = [];
public function __construct($data)
{
$this->data= $data;
}
public function handle()
{
// Process uploaded
}
}
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 ?
作业完成后我需要检查一些数据,但我从$event->job->payload()
in 中获取了序列化数据
Queue::after
而且我不明白如何检查作业?
回答by Bondan Sebastian
Well, to test the logic inside handle
method you just need to instantiate the job class & invoke the handle
method.
好吧,要测试handle
方法内部的逻辑,您只需要实例化作业类并调用该handle
方法。
public function testJobsEvents()
{
$job = new \App\Jobs\YourJob;
$job->handle();
// Assert the side effect of your job...
}
Remember, a job is just a class after all.
请记住,工作毕竟只是一个班级。
回答by sumeet
Synchronous Dispatching
同步调度
If you would like to dispatch a job immediately (synchronously), you may use the dispatchNow method. When using this method, the job will not be queued and will be run immediately within the current process:
如果您想立即(同步)调度作业,您可以使用 dispatchNow 方法。使用此方法时,作业不会排队,会立即在当前进程内运行:
Job::dispatchNow()
Job::dispatchNow()