首页 > 解决方案 > Laravel:我怎样才能伪造一个 http 请求到第 3 方和模拟 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。当端点位于我的应用程序本地时(不调用第 3 方),我已经成功地进行了此测试。这是我过去所做的:

$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']),
]);

如何模拟/伪造对 3rd 方 url 的请求并断言良好的响应?感谢您的任何建议!

标签: laraveltestingphpunitlaravel-7

解决方案


根据文档(和您的问题),您可以传递一个数组来Http::fake()指定您想要哪些请求的响应,即key请求 url 和值是模拟响应。

您的测试将类似于:

$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', ...]);;

推荐阅读