Dam*_*mon 3 testing phpunit laravel laravel-7
我正在努力弄清楚什么可能是非常基本的东西,我会被嘲笑离开这里,但我希望也许它也能对其他人有所帮助。
我正在尝试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);
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我的请求如下所示:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我想模拟我收到 200 响应,并且理想情况下模拟来自资源的预期 json。当端点位于我的应用程序本地时(不调用第三方),我已经成功地进行了此测试。这就是我过去所做的:
$http->assertStatus(200)
->assertJsonStructure([
'type', 'id', 'attributes' => [
'email', 'uuid', 'created_at', 'updated_at',
],
])
->assertJson(['type' => 'example',...]);
Run Code Online (Sandbox Code Playgroud)
在文档中我可以看到这个:
Http::fake([
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
]);
Run Code Online (Sandbox Code Playgroud)
如何模拟/伪造对第 3 方 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', ...]);;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14336 次 |
| 最近记录: |