首页 > 解决方案 > Laravel TestCase-> postJson 到外部网址?

问题描述

我正在尝试编写一个 Laravel 测试用例,我需要向外部 API 发出 HTTP Post 请求。但我$this->postJson()一直给我一个例外。这是我的代码的摘录:

namespace Tests\Feature;

use Tests\TestCase;

class PurchaseTest extends TestCase
{

    protected function setUp(): void
    {
        parent::setUp();
    }

    public function testPurchasePolicy()
    {
        $response = $this->postJson('https://apitest.cybersource.com/flex/v1/',['cardNumber'=>'4111111111111111']);
        print_r($response->json());
        $response->assertOk();
    }
}

这给出了结果:

Array
(
    [message] =>
    [exception] => Symfony\Component\HttpKernel\Exception\NotFoundHttpException
    [file] => /var/www/projects/local/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php
    [line] => 43
    [trace] => Array
 (
            [0] => Array
                (
                    [file] => /var/www/projects/local/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php
                    [line] => 162
                    [function] => handleMatchedRoute
                    [class] => Illuminate\Routing\AbstractRouteCollection
             ///  --> then a stack trace of laravel code that failed
)

您将无法完全运行我的代码,因为它需要一些带有网络资源的 API 密钥。但我很确定我的代码失败了,因为我没有正确地告诉 Laravel 我要访问的 API 是外部资源。

Laravel 连接外部 URL 的惯用方式是什么?

标签: laravelunit-testingtesting

解决方案


您必须使用 HTTP 客户端。

  1. 使用作曲家安装 guzzle:

composer require guzzlehttp/guzzle

然后:

对于 laravel 7.x 及更高版本,使用 HTTP Client 外观:

use Illuminate\Support\Facades\Http;

$response = Http::get('http://test.com');

查看有关HTTP 客户端使用的 laravel 文档。

对于 laravel 6.x 或更低版本,使用 guzzle 如下:

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]); 

检查Guzzle 文档。


推荐阅读