每个测试用例的symfony覆盖参数

tsm1rwdh  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

假设我有一个类,它只对特定的路由执行某些操作,这些路由名称存储在service.yaml

parameters:
    supported_routes: ['route1', 'route2']

我想写几个测试案例:

  • testIgnoreRoute 1 IfRouteNotSupported-我想将supported_routes列表更改为排除route1
  • testIgnoreRoute 2 IfRouteNotSupported-我想将supported_routes列表更改为排除route2
  • testPerformanceIfRoute 1 Supported-我希望在supported_routes中包含route1
  • testPerformanceIfRoute 2Supported-我希望在supported_routes中包含route2

我怎么能这么做呢?由于容器被冻结,不允许动态更改容器参数。可以使用测试service.yaml覆盖service.yaml,但在这种情况下,即使它可以与主列表不同,它仍然是所有测试的相同列表。此外,可以将该列表存储在env中,但我不认为这是一个好主意,因为我不希望它在一个真实的应用程序中依赖于env。
我知道你可以告诉我为什么不写一个单元测试,模拟你需要的东西,这不像我的真实的应用程序那么容易,第三方库使用列表作为库配置的一部分,所以它应该是集成/功能测试。

qzwqbdag

qzwqbdag1#

我现在唯一能想到的是,我不知道我是否正确理解了你的问题。
您可以为测试定义不同的环境,并相应地调用它们。

service.yaml

when@test: &route_test
    parameters:
        supported_routes: ['route1', 'route2']

when@testroute1:
    framework:
        test: true
    parameters:
        supported_routes: ['route1']

when@testroute2:
    framework:
        test: true
    parameters:
        supported_routes: ['route2']

使用APP_ENV=<envname> php bin/phpunit --filter ServiceTest启动相应的测试。

<?php

namespace App\Tests\SO77229710;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class ServiceTest extends KernelTestCase
{
    /**
     * @var ParameterBagInterface
     */
    private mixed $parameters;

    public function setUp(): void
    {
        parent::setUp();
        self::bootKernel();
        $this->parameters = self::getContainer()->get(ParameterBagInterface::class);
    }

    /**
     * APP_ENV=testroute1 php bin/phpunit --filter ServiceTest
     */
    public function testRoute1()
    {
        if ('testroute1' !== self::$kernel->getEnvironment()) {
            $this->markTestSkipped('Skipped because is not APP_EN testroute1');
        }

        $this->assertEquals(['route1'], $this->parameters->get('supported_routes'));
    }

    /**
     * APP_ENV=testroute2 php bin/phpunit --filter ServiceTest
     */
    public function testRoute2()
    {
        if ('testroute2' !== self::$kernel->getEnvironment()) {
            $this->markTestSkipped('Skipped because is not APP_EN testroute2');
        }

        $this->assertEquals(['route2'], $this->parameters->get('supported_routes'));
    }
}

更新

将APP_ENV设置为动态。

class ServiceTest extends KernelTestCase
{
    public function testRoute1()
    {
        self::bootKernel(['environment' => 'testroute1']);
        $parameters = self::getContainer()->get(ParameterBagInterface::class);
        $this->assertEquals(['route1'], $parameters->get('supported_routes'));
    }

    public function testRoute2()
    {
        self::bootKernel(['environment' => 'testroute2']);
        $parameters = self::getContainer()->get(ParameterBagInterface::class);
        $this->assertEquals(['route2'], $parameters->get('supported_routes'));
    }
}

相关问题