【问题标题】:How to test the method that makes http request?如何测试发出http请求的方法?
【发布时间】:2020-08-05 02:56:24
【问题描述】:

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

PHP 7.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;
    }
}

【问题讨论】:

    标签: php laravel unit-testing phpunit


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      要创建新的测试用例,可以使用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();
          }
      }
      

      这是一个简单的示例,您可以根据需要对其进行修改。 在 laravel 中查看更多内容docs

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-21
          • 2016-07-18
          • 1970-01-01
          相关资源
          最近更新 更多