我一直在自学如何编写测试用例,但我不知道如何测试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。
发布于 2018-03-05 04:51:52
测试Json作业有点棘手,因为您必须测试它是否是队列的、调度的,然后您就可以知道是否要接收响应,以及它是否是预期的响应。
为了保持它的简单性和有用性,我将函数划分为3个测试(调度、队列和结果),这样您就可以测试每个进程,并且可以扩展更多来测试
队列: 队列
总线: 总线命令
如果您对同一个页面感兴趣,您可以在队列测试中找到更多的参考在这里,对于命令总线也可以找到相同的。
这是测试类:
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Support\Facades\Queue; // includes the fake method
use Illuminate\Support\Facades\Bus; // includes the fake method
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Bus\DispatchesJobs; // for the Queue
use Illuminate\Foundation\Bus\Dispatcher; // for the Bus
use App\Jobs\APIjob 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",
],
]);
}
}
https://stackoverflow.com/questions/49105324
复制相似问题