laravel - 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 的请求并断言良好的响应?感谢您的任何建议!
解决方案
根据文档(和您的问题),您可以传递一个数组来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', ...]);;
推荐阅读
- c# - “限定在该命名空间中使用类型”的语句在 C# 中是什么意思
- android - Android TV-leanback 库如何向 VideoSupportFragmentGlueHost 添加更多按钮
- pdf - 从 PDF C# 中提取的国家字符/Unicode 字符
- r - 如何在包中使依赖项成为可选
- swift - 将类类型作为函数参数传递并用作?铸造班级
- apache-spark - 如何在 Spark 中按其他 DataFrame 中的条件过滤 DataFrame
- javascript - 如果属性与数组中的值匹配,则过滤对象
- java - 目标无法到达,“汽车”返回 null
- angular - 哪个日期范围选择器最适合与角度 6 一起使用
- scala - 如何在scala中找到不同的ngram?