首页 > 解决方案 > Symfony 5.2 模拟服务在第二个请求中消失

问题描述

我使用了 Symfony 5.2,我需要模拟执行发送请求到条带支付系统的服务方法,显然在测试执行时不需要执行它,所以我遇到了这个问题,当请求发送超过一次时

配置/services_test.yaml:

App\Service\StripeService:
    public: true
    lazy: true

我的测试班

namespace App\Tests;

use App\Document\User;
use App\Service\StripeService;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as SymfonyWebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;

abstract class WebTestCase extends SymfonyWebTestCase
{
    private ?string $accessToken;

    protected ?KernelBrowser $client;

    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        parent::setUp();
        $this->client = static::createClient();

        $mockStripeService = $this->getMockBuilder(StripeService::class)
            ->disableOriginalConstructor()
            ->getMock();

        $mockStripeService
            ->expects($this->once())
            ->method('createCustomer');

        $this->getContainer()->set(StripeService::class, $mockStripeService);

当第一个请求被执行并在同一个测试函数中调用另一个请求时,模拟被替换为原始类,为什么?

模拟行为正确,模拟服务替换原来的

$this->postJson('/api/register', $userDetails);

在调用模拟服务之前仍然存在于容器中

$this->postJson('/api/login', [
            'username' => $user->getUsername(),
            'password' => 'IncorrectPassword'
        ]
    );

但是在第二个请求中由于某种原因模拟消失并出现原始服务类

标签: symfonymockingphpunit

解决方案


推荐阅读