unit-testing - 功能测试中的 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.
解决方案
你不应该注入Request
你的服务。您应该使用Symfony\Component\HttpFoundation\RequestStack
而不是Request
. 此外,您应该检查 if $requestStack->getCurrentRequest()
doesn't return null
。我想你在容器初始化的过程中遇到了这样的错误,但你只执行了一个脚本(测试),当然,你没有Request
它。
推荐阅读
- android - 从当前的 html 文件 Android Studio 打开本地 html 文件?
- function - 如何将 raw_input 与函数一起使用并在 Git Bash 中获取输出?
- r - 从 R 中具有相同 ID 的行创建新变量(在新列中但不创建新列)
- c# - 更新
在 App.config winForm C# - postgresql - 无法访问在单独的 docker 容器中运行的 postgres
- javascript - 使用更改变量调用本地存储
- tomcat - 无法使用 POSTMAN 将数据发布到 Apache Tomcat 服务器
- copy - 不使用 tablemodel 克隆 JTable
- node.js - 另一台电脑上的 Debugger-ui
- java - 在java中的主类中设置一个类中的数组大小