php - 使用 PHP 匿名类进行测试和模拟

标签 php unit-testing symfony phpunit php-7

我正在尝试使用匿名类测试和模拟一段代码。这是代码:

<?php

namespace App\Service;

use Symfony\Contracts\HttpClient\HttpClientInterface;

class FetchPromoCodeService
{
    private $client;

    public function __construct(HttpClientInterface $client)
    {
        $this->client = $client;
    }

    public function getPromoCodeList(): array
    {
        $response = $this->client->request(
            'GET', 'https://xxxxxxxxx.mockapi.io/test/list'
        );

        return $response->toArray();
    }
}

这是我的测试类:

<?php

namespace App\Tests\Service;

use App\Service\FetchPromoCodeService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\JsonResponse;

class FetchPromoCodeServiceTest extends TestCase
{

    public function testGetPromoCodeList()
    {
        $fetchPromoCodeService = new class () extends FetchPromoCodeService {
            public $client;

            public function __construct($client)
            {
                $this->client = (new JsonResponse(['a' => 1, 'b' => 2]))->getContent();
                parent::__construct($client);
            }
        };

        $result = $fetchPromoCodeService->getPromoCodeList();

        $this->assertIsArray($result);
    }
}

我需要测试 getPromoCodeList() 方法,所以我想模拟 http 调用。 测试的目的是确保我们将结果调用转换为 php 数组。

但我的问题是 FetchPromoCodeService 构造函数。我在执行命令时出现此错误。

ArgumentCountError: Too few arguments to function class@anonymous::__construct(), 0 passed in /var/www/html/tests/Service/FetchPromoCodeServiceTest.php on line 14 and exactly 1 expected

我知道它正在等待 HttpClientInterface 类型的参数,但我知道有一种方法可以覆盖它,因为我只想模拟 client 属性。我只是不记得我该怎么做。

我如何在 php 和匿名类中做到这一点?

最佳答案

虽然您可以使用匿名类实现您想要的,但 Symfony HTTP 客户端附带的模拟客户端可能是更简单的解决方案:

<?php

namespace App\Tests\Service;

use App\Service\FetchPromoCodeService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;

final class FetchPromoCodeServiceTest extends TestCase
{
    public function testGetPromoCodeList()
    {
        $client = new MockHttpClient([new MockResponse(json_encode(['a' => 1, 'b' => 2]))]);

        $result = (new FetchPromoCodeService($client))->getPromoCodeList();

        self::assertIsArray($result);
    }
}

关于php - 使用 PHP 匿名类进行测试和模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66286664/

相关文章:

php - Javascript 数组不会注意到文件夹中的新图像

PHP:从字符串中提取数字的最佳方法

javascript - Vue 内容在父组件之外渲染

java - 使用 SpringSecurity 和 Mock 进行 Spring Boot 单元测试

php - 使用 Symfony2 的自定义注释的简单示例

php - Symfony 2 上的 Endroid/Qrcode 和 __DIR__ const 出现内部服务器错误

php - 为 PHP 5 编译 SQLite 的设置是什么?

node.js - 如果在测试过程中无法重现错误,如何测试 catch 子句?

unit-testing - SenTestKit : cleaning up after ALL tests have run?

php - 如何将 andWhere 和 orWhere 与 Doctrines Criteria 结合起来