首页 > 解决方案 > 功能测试中的 Symfony 4 Mock 服务

问题描述

我正在测试一项服务,该服务主要是序列化一个对象并通过服务将其发送到外部系统。

如果我创建典型的单元测试,我会模拟序列化程序和服务的响应,它们与外部系统联系。事实上,除了在我的对象中调用一堆 setter 方法之外,没有太多需要测试的东西了。

另一种方法是使用 KernelTestCase 并创建一个功能测试,这很好,除非我不想联系外部系统,而是只对这个“外部”服务使用模拟。

有没有可能在 Symfony 4 中实现这一点?或者有另一种方法吗?

我现在正在做的事情如下:

<?php

namespace App\Tests\Service;

use App\Service\MyClassService;
use App\Service\ExternalClient\ExternalClient;
use JMS\Serializer\Serializer;
use JMS\Serializer\SerializerInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\HttpFoundation\Request;

class MyClassServiceTest extends KernelTestCase
{
    /** @var LoggerInterface */
    private $logger;

    /** @var Serializer */
    private $serializer;

    /** @var ExternalClient */
    private $externalClient;

    /** @var RequestInterface */
    private $request;

    /** @var MyClassService */
    private $myClassService;

    public function setUp()
    {
        $kernel = self::bootKernel();

        $this->logger = $kernel->getContainer()->get(LoggerInterface::class);
        $this->serializer = $kernel->getContainer()->get(SerializerInterface::class);
        $this->externalClient = $this->createMock(ExternalClient::class);
    }

    public function testPassRegistrationData()
    {
        $getParams = [
            'amount'          => '21.56',
            'product_id'      => 867,
            'order_id'        => '47t34g',
            'order_item_id'   => 2,
            'email'           => 'kiki%40bubu.com',
        ];

        $this->generateMyClassService($getParams);

        $userInformation = $this->myClassService->passRegistrationData();
        var_dump($userInformation);
    }

    /**
    * generateMyClassService
    *
    * @param $getParams
    *
    * @return MyClass
    */
    private function generateMyClassService($getParams)
    {
        $this->request = new Request($getParams, [],  [], [], [], [], null);

        $this->myClassService = new MyClassService(
            $this->logger,
            $this->serializer,
            $this->externalClient,
            $this->request
        );
    }
}

退回此错误:

Symfony\Component\DependencyInjection\Exception\RuntimeException: Cannot autowire service "App\Service\MyClassConfirmationService": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists.

标签: unit-testingsymfony4

解决方案


你不应该注入Request你的服务。您应该使用Symfony\Component\HttpFoundation\RequestStack而不是Request. 此外,您应该检查 if $requestStack->getCurrentRequest()doesn't return null。我想你在容器初始化的过程中遇到了这样的错误,但你只执行了一个脚本(测试),当然,你没有Request它。


推荐阅读