Laravel:如何伪造对第三方的HTTP请求和模拟JSON响应

问题描述

我正在努力弄清什么是最基本的东西,我会在这里笑出来,但我希望它也能对其他人有所帮助。

我正在尝试模拟/测试功能测试中的Http请求。我仍在学习好的/更好/最好的测试技术,所以也许有更好的方法

// MyFeatureTest.PHP

$user = factory(User::class)->create(['email' => 'example@email.com']);

// Prevent actual request(s) from being made.
Http::fake();

$this->actingAs($user,'api')
    ->getJson('api/v1/my/endpoint/123456')
    ->assertStatus(200);

在我的控制器中,我的请求如下所示:

public function myFunction() {
    try {
        $http = Http::withHeaders([
                'Accept' => 'application/json','Access_Token' => 'my-token','Content-Type' => 'application/json',])
            ->get('https://www.example.com/third-party-url,[
                'foo' => 'bar,]);

            
        return new MyResource($http->json());
    } catch (RequestException $exception) {
        Log::error("Exception error: " . print_r($exception,true));
    }
}

我想模拟一下,我得到一个200的响应,并且理想地从资源中模拟出期望的json。当端点在我的应用程序本地时(不呼叫第三方),我已经能够成功执行此测试。这是我过去所做的:

$http->assertStatus(200)
    ->assertJsonStructure([
        'type','id','attributes' => [
            'email','uuid','created_at','updated_at',],])
    ->assertJson(['type' => 'example',...]);

在文档中,我可以看到以下内容

Http::fake([
    'github.com/*' => Http::response(['foo' => 'bar'],200,['Headers']),]);

如何模拟/伪造对第三方URL的请求并断言良好的响应?谢谢您的任何建议!

解决方法

您可以使用

use GuzzleHttp\Handler\MockHandler;

您的myFunction代码将类似于

$mock = new MockHandler([
        new Response(200,[],File::get(base_path('your-mock-response-success.json'))),]);

    $handler = HandlerStack::create($mock);

    $client = new Client(['handler' => $handler]);

    $mock = $this->mock(YourService::class);
    $mock->shouldReceive('create')
        ->andReturn($client);
,

根据docs(和您的问题),您可以将数组传递给Http::fake(),以指定您希望针对哪些请求的响应,即key是请求的网址,值是模拟的响应。

您的测试将类似于:

$user = factory(User::class)->create(['email' => 'example@email.com']);

Http::fake([
    'www.example.com/third-party-url' => Http::response([
        'type'       => 'example','id'         => 'some id','attributes' => [
            'email'      => 'some email','uuid'       => 'some uuid','created_at' => 'some created_at','updated_at' => 'some updated_at',],200),]);

$this->actingAs($user,'api')
     ->getJson('api/v1/my/endpoint/123456')
     ->assertStatus(200)
     ->assertJsonStructure([
         'type','id','attributes' => [
             'email','uuid','created_at','updated_at',])
     ->assertJson(['type' => 'example',...]);;