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

Php 如何测试发出http请求的方法?,php,laravel,unit-testing,phpunit,Php,Laravel,Unit Testing,Phpunit,我正在用拉威尔写测试。 然而,我遇到了麻烦,因为我不知道如何测试。 有一种方法可以发出http请求,如下所示。 您通常如何测试此方法? 我应该使用实际可访问的URL还是mock PHP 7.4.6 拉威尔7.0 <?php namespace App\Model; use Illuminate\Support\Facades\Http; use Exception; class Hoge { public function getText(string $url, ?stri

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

PHP 7.4.6 拉威尔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测试

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

php artisan make:test HogeTest
然后,您可以创建HogeTest,因为您的头是正确的

<?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();
    }
}

与其他系统联系的功能可能会很慢,并且使测试变得脆弱。不过,您需要确保
getText
方法按预期工作。我会这样做:

  • 仅为您的
    getText
    方法创建一组集成测试。这些测试向服务器发出实际的http请求,以验证预期的行为。web服务器不必是外部系统。您可以使用php提供测试URL。你可以找到一篇文章来指导你的方向

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