php - 对 Symfony 服务类进行单元测试

标签 php unit-testing symfony symfony4

我正在寻找一些有关如何为 Symfony Service 类编写单元测试的指导。一整天都在网上搜寻,但我最发现的是有关旧 phpunit 版本和旧 Symfony 版本的过时问题和答案。

我正在运行 Symfony 4 并且有一个名为 ApiService.php 的服务类。此类连接到外部 API 服务,我不是在考虑测试此外部 API 服务,而是使用固定数据集测试我自己的方法。

该类的一个非常精简的版本如下所示,位于文件夹src/Service/ApiService.php中:

<?php

namespace App\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Uri;
use JsonException;

class ApiService
{
    /**
     * Set if test environment is enabled
     *
     * @var    bool
     * @since  1.0.0
     */
    private bool $test;

    /**
     * User key for API authentication
     *
     * @var    string
     * @since  1.0.0
     */
    private string $userKey;

    /**
     * Construct the class.
     *
     * @param   bool    $test  Set API mode
     * @param   string  $key   Set the API token
     *
     * @since   1.0.0
     */
    public function __construct(bool $test, string $key)
    {
        $this->userKey = $key;
        $this->test    = $test;
    }

    /**
     * Search companies.
     *
     * @param   array  $params     Parameters to filter the query on
     * @param   array  $companies  List of retrieved companies
     *
     * @return  array  List of companies.
     *
     * @since   1.0.0
     * @throws  JsonException
     * @throws  GuzzleException
     */
    public function getCompanies(array $params, array $companies = []): array
    {
        $results = $this->callApi('search/companies', $params);

        if (isset($results['data']['items'])) {
            $companies = array_merge(
                $companies,
                $results['data']['items']
            );
        }

        $nextLink = $results['data']['nextLink'] ?? null;

        if ($nextLink) {
            $uri = new Uri($nextLink);
            parse_str($uri->getQuery(), $params);
            $companies = $this->getCompanies($params, $companies);
        }

        return $companies;
    }

    /**
     * Call the API.
     *
     * @param   string  $destination  The endpoint to call
     * @param   array   $params       The parameters to pass to the API
     *
     * @return  array  API details.
     *
     * @since   1.0.0
     * @throws  GuzzleException|JsonException
     */
    private function callApi(string $destination, array $params = []): array
    {
        $client = new Client(['base_uri' => 'https://test.com/']);

        if ($this->test) {
            $destination = 'test' . $destination;
        }

        if ($this->userKey) {
            $params['user_key'] = $this->userKey;
        }

        $response = $client->get($destination, ['query' => $params]);

        return json_decode(
            $response->getBody()->getContents(),
            true,
            512,
            JSON_THROW_ON_ERROR
        );
    }
}

这是我迄今为止完成的测试类,但它不起作用:

<?php

namespace App\Tests\Service;

use App\Service\ApiService;
use PHPUnit\Framework\TestCase;

class ApiServiceTest extends TestCase
{
    public function testGetCompanies()
    {
        $result = ['data' => [
            'items' => [
                1 => 'first',
                2 => 'second'
            ]
        ];

        $apiService = $this->getMockBuilder(ApiService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $apiService->method('callApi')
            ->with($result);

        $result = $apiService->getCompanies([]);

       print_r($result);
    }
}

我不明白的是一些事情。

首先我应该扩展哪个类:

  • 测试用例
  • WebTestCase
  • 内核测试用例

第二,如何设置模拟数据,这样我就不会使用外部 API,而是传递我定义的 $result

如前所述,我并不是要测试外部 API,而是希望在给定要测试的示例数据的情况下,我的方法始终按照测试中设计的方式运行。

任何提示将不胜感激。

最佳答案

您应该从 PHPUnit 的 TestCase 进行扩展。如果您想进行功能测试,WebTestCaseKernelTestCase 非常有用。您的案例是一个经典的单元测试:您想要单独测试您的 ApiService

ApiService 目前实际上正在做两件事:

  • 调用电话
  • 处理数据

通过引入专用的 API 客户端将两者分开是一个好主意:

interface ApiClient
{
    public function call(string $destination, array $params = []): array;
}

对于您的生产代码,您可以使用 Guzzle 创建一个实现。您可以为发出实际 http 请求的 GuzzleApiClient 编写集成测试,以确保它以预期方式处理响应。

您的 ApiService 现在可以归结为:

final class ApiService
{
    private ApiClient $apiClient;

    public function __construct(ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
    }

    public function getCompanies(array $params, array $companies = []): array
    {
        $results = $this->apiClient->call('search/companies', $params);

        if (isset($results['data']['items'])) {
            $companies = array_merge(
                $companies,
                $results['data']['items']
            );
        }

        $nextLink = $results['data']['nextLink'] ?? null;

        if ($nextLink) {
            parse_str(parse_url($nextLink, PHP_URL_QUERY), $params);

            $companies = $this->getCompanies($params, $companies);
        }

        return $companies;
    }
}

由于我不知道 ApiService 到底是做什么的,所以我编写了这些示例测试:

/**
 * @covers \App\Service\ApiService
 */
class ApiServiceTest extends TestCase
{
    /**
     * @var MockObject&ApiClient
     */
    private ApiClient $apiClient;

    private ApiService $subject;

    public function testGetCompanies()
    {
        $this->apiClient->addResponse(
            'search/companies',
            [],
            ['data' => ['items' => [1 => 'first', 2 => 'second']]]
        );

        $result = $this->subject->getCompanies([]);

        self::assertEquals(['first', 'second'], $result);
    }

    public function testGetCompaniesPaginated()
    {
        $this->apiClient->addResponse(
            'search/companies',
            [],
            ['data' => ['items' => [1 => 'first', 2 => 'second'], 'nextLink' => 'search/companies?page=2']]
        );
        $this->apiClient->addResponse(
            'search/companies',
            ['page' => 2],
            ['data' => ['items' => [1 => 'third', 2 => 'fourth'], 'nextLink' => 'search/companies?page=3']]
        );
        $this->apiClient->addResponse(
            'search/companies',
            ['page' => 3],
            ['data' => ['items' => [1 => 'fifth']]]
        );


        $result = $this->subject->getCompanies([]);

        self::assertEquals(['first', 'second', 'third', 'fourth', 'fifth'], $result);
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->apiClient = new class implements ApiClient {
            private array $responses = [];

            public function call(string $destination, array $params = []): array
            {
                return $this->responses[$this->key($destination, $params)] ?? [];
            }

            public function addResponse(string $destination, array $params, array $response)
            {
                $this->responses[$this->key($destination, $params)] = $response;
            }

            private function key(string $destination, array $params): string
            {
                return $destination . implode('-', $params);
            }
        };

        $this->subject = new ApiService($this->apiClient);
    }
}

我为 ApiClient 实现创建了一个匿名类。这只是一个例子。当然,您也可以使用 PHPUnit 的模拟、Prophecy 或您喜欢的任何模拟框架。但我发现创建专门的测试替身通常更容易。

关于php - 对 Symfony 服务类进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63290170/

相关文章:

javascript - 点击提交时打开JS弹窗

php - Wordpress 中的标签颜色不同?

access-control - Symfony2 - 访问控制

c# - 你如何对 tcp 连接进行单元测试?

python-3.x - 如何在 python 中正确模拟 gcp 客户端库调用

php - Symfony 缓存默认文件夹路径

symfony - 在为现有数据库创建实体和存储库后生成初始迁移

PHP:从日期字符串中搜索缺失的日期

javascript - 我需要对 HTML 和 JavaScript 代码进行哪些更改才能使 character_count 正常工作?

java - 是否有一个等效的 doCallRealMethod 用于 spy (又名 doCallMockMethod)?