laravel - 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 的惯用方式是什么?
解决方案
您必须使用 HTTP 客户端。
- 使用作曲家安装 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']
]);
推荐阅读
- java - 如何显示下拉列表的某些选定值
- keras - 无法在多标签分类器上使用 Stratified-K-Fold
- jenkins - BlueOcean 在并行阶段之前未显示输入
- asp.net - 如何在 asp.net 报表查看器中显示数据库中保存的二维码
- python - 需要将抓取的数据写入 csv 文件(线程)
- node.js - 适用于 Node.js 的 Twilio Lookup API - 验证并获取 E.164 格式
- vue.js - jest.fn() 声称没有被调用,但有
- html - 如何创建半透明的模糊叠加层?
- arangodb - 查询多个集合 Arangodb
- checkbox - 在 Google 表格中选中复选框时复制另一张表格中的行