如何测试发出http请求的方法?

How to test the method that makes http request?

我正在 Laravel 中编写测试。 但是,我遇到了麻烦,因为我不知道如何测试。 有一种方法可以发出http请求,如下所示。 您通常如何测试此方法? 我应该使用实际可访问的 URL 还是 mock?

PHP7.4.6 Laravel 7.0

<?php

namespace App\Model;

use Illuminate\Support\Facades\Http;
use Exception;

class Hoge
{
    public function getText(string $url, ?string $user, ?string $password, string $ua): bool
    {
        $header = ["User-Agent" => $ua];
        $httpObject = $user && $password ? Http::withBasicAuth($user, $password)->withHeaders($header) : Http::withHeaders($header);

        try {
            $response = $httpObject->get($url);
            if ($response->ok()) {
                return $response->body();
            }
        } catch (Exception $e) {
            return false;
        }

        return false;
    }
}

我更喜欢使用 Postman 进行 Web 服务器/API 测试。 https://www.postman.com/downloads/

要创建新的测试用例,可以使用make:test Artisan命令:

php artisan make:test HogeTest

然后你可以创建你的 HogeTest,考虑到你的 headers 是正确的

<?php

namespace Tests\Feature;

use Tests\TestCase;

class HogeTest extends TestCase
{  
    public function hogeExample()
    {
        $header = ["User-Agent" => $ua];
        $response = $this->withHeaders([
            $header,
        ])->json('POST', $url, ['username' => $user, 'password' => $password]);

        $response->assertStatus(200);
      // you can even dump response
      $response->dump();
    }
}

这是一个简单的示例,您可以如何根据需要修改它。 在 laravel docs

中查看更多内容

扩展到其他系统的功能可能会很慢并使测试变得脆弱。不过,您希望确保 getText 方法按预期工作。我会做以下事情:

  • 为您的 getText 方法创建一组集成测试。这些测试向服务器发出实际的 http 请求以验证预期的行为。 Web 服务器不必是外部系统。您可以使用 php 的 built in webserver to provide test urls. You can find an article here 来指导您。

  • 对于使用 getText 方法的所有其他功能,我会模拟该方法以保持快速测试。