Laravel 5:如何测试调用API的Jobs?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel 5:如何测试调用API的Jobs?相关的知识,希望对你有一定的参考价值。
我一直在教自己如何编写测试用例,但我对如何测试Job
是否调用API(并声明API已获得预期响应)无能为力。
这是我的实验的片段......
Class SampleJob extends Job
{
public function handle()
{
$request->method('post')->setUrl('/blahblah')->setBody($body);
//For the sake of convenience, let me just state that
//$request calls an API call.
//i.e. If it's successful, you'll get
//HTTP status 200 and a JSON object
}
}
Class SampleJobTest extends TestCase
{
use DispatchesJobs;
/** @test */
public function it_calls_api()
{
$data = factory(MockData::class)->create();
$this->dispatch(new SampleJob($data));
//assert that the API was called
//assert that there was an HTTP response - status & JSON
}
}
正如评论中提到的那样,是否有可能断言API是用预期的响应调用的?
任何建议将被认真考虑。
编辑
调度SampleJob时,将调用API。
测试Json API作业有点棘手,因为您必须测试它是否已排队,调度,然后您将知道是否要接收响应以及是否是预期响应。
保持简单和有用;我将这些函数分成3个测试(调度,队列和结果),这样你就可以测试每个进程,你可以进一步扩展以测试
队列:Queue
- 哪个队列被推了工作?
- 多少次?
- 发送或阻止?
公共汽车:Bus command
- 发送或阻止?
如果您对同一页面感兴趣,可以在队列测试中找到更多reference here,对于命令总线也可以找到相同的<?php
namespace TestsUnit;
use TestsTestCase;
use IlluminateSupportFacadesQueue; // includes the fake method
use IlluminateSupportFacadesBus; // includes the fake method
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateFoundationBusDispatchesJobs; // for the Queue
use IlluminateFoundationBusDispatcher; // for the Bus
use AppJobsAPIjob as Job; // your job goes here
class ExampleTest extends TestCase
{
use DispatchesJobs;
/**
* Setup the test environment. // to make the environment as a usual Laravel application which includes the helpers functions.
*
* @return void
*/
protected function setup(){
parent::setUp();
}
/**
* A basic dispatch example.
*
* @return void
* @test
*/
public function it_dispatches(){
Bus::fake(); // faking the Bus command
$job = new Job;
Bus::dispatch($job);
Bus::assertDispatched(Job::class, 1);
}
/**
* A basic queue example.
*
* @return void
* @test
*/
public function it_queues(){
Queue::fake(); // faking Queue using the facade
$job = new Job;
Queue::push($job); // manually pushing the job to the Queue
$this->dispatch($job);
Queue::assertPushed(Job::class, 1);
}
/**
* A basic receive example.
*
* @return void
* @test
*/
public function it_recieves_api(){
$response = $this->get('/APIroute'); // change this to match the route which you will receive the Json API from.
$response->assertStatus(200) //
->assertJsonFragment([ // using Fragment if partial, you can remove the word Fragment for full match
[
'id' => 1,
"name" => "Emely Jones",
"email" => "sgleichner@example.com",
"created_at" => "2018-03-05 16:36:14",
"updated_at" => "2018-03-05 16:36:14",
],
]);
}
}
。
这是测试类:
qazxswpoi
以上是关于Laravel 5:如何测试调用API的Jobs?的主要内容,如果未能解决你的问题,请参考以下文章
Laravel API 测试 - 如何测试具有外部 API 调用的 API
如何测试 Laravel 5.4 中的“创建”事件是不是调用了 Eloquent 模型方法?