如何测试Symfony6.1中基于AbstractBundle的新配置模式?
测试Symfony AbstractBundle中configure方法的配置定义
自Symfony 6.1起,Bundle可直接继承AbstractBundle,将配置定义逻辑整合到configure方法中。要测试这个方法里的配置规则,你可以通过手动构建配置树的方式,复用Symfony的配置处理器来验证,具体步骤如下:
核心思路
- 实例化你的Bundle类;
- 创建
TreeBuilder和DefinitionConfigurator实例,传递给Bundle的configure方法,让它生成配置树; - 使用
Processor处理测试配置,验证配置的合法性、处理结果是否符合预期。
示例测试代码
以AcmeSocialBundle为例,编写对应的配置测试类:
namespace Acme\SocialBundle\Tests; use Acme\SocialBundle\AcmeSocialBundle; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\Definition\TreeBuilder; use Symfony\Component\Yaml\Yaml; class AcmeSocialBundleConfigTest extends TestCase { // 测试空配置的处理结果 public function testEmptyConfiguration(): void { $bundle = new AcmeSocialBundle(); // 初始化配置树构建器和配置定义器 $treeBuilder = new TreeBuilder('acme_social'); $definitionConfigurator = new DefinitionConfigurator($treeBuilder); // 触发Bundle的configure方法生成配置规则 $bundle->configure($definitionConfigurator); // 构建配置树并处理空配置 $configTree = $treeBuilder->buildTree(); $processor = new Processor(); $processedConfig = $processor->process($configTree, [[]]); // 验证空配置结果为空数组 $this->assertEmpty($processedConfig); } // 测试合法Twitter配置的处理结果 public function testValidTwitterConfiguration(): void { $bundle = new AcmeSocialBundle(); $treeBuilder = new TreeBuilder('acme_social'); $definitionConfigurator = new DefinitionConfigurator($treeBuilder); $bundle->configure($definitionConfigurator); $configTree = $treeBuilder->buildTree(); // 加载合法的YAML配置 $yamlConfig = Yaml::parse(<<<YAML twitter: client_id: 12345 client_secret: my-secret-key YAML); $processor = new Processor(); $processedConfig = $processor->process($configTree, [$yamlConfig]); // 验证配置处理后的结构和值 $this->assertEquals([ 'twitter' => [ 'client_id' => 12345, 'client_secret' => 'my-secret-key' ] ], $processedConfig); } // 测试非法配置的异常抛出 public function testInvalidTwitterClientId(): void { // 预期抛出类型错误异常 $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); $bundle = new AcmeSocialBundle(); $treeBuilder = new TreeBuilder('acme_social'); $definitionConfigurator = new DefinitionConfigurator($treeBuilder); $bundle->configure($definitionConfigurator); $configTree = $treeBuilder->buildTree(); // 加载非法配置:client_id为字符串而非整数 $yamlConfig = Yaml::parse(<<<YAML twitter: client_id: "not-an-integer" client_secret: my-secret-key YAML); $processor = new Processor(); $processor->process($configTree, [$yamlConfig]); } }
关键说明
- 手动创建
TreeBuilder时,参数需要和Bundle配置的根节点名称对应(示例中为acme_social); - 可以通过这种方式测试所有配置规则,包括类型约束、默认值、必填项等;
- 测试逻辑和传统
Configuration类的测试流程一致,只是获取配置树的方式从实例化Configuration类改为调用Bundle的configure方法。
内容的提问来源于stack exchange,提问作者Alexandre Tranchant
相关产品推荐
相关产品推荐

