在Symfony2中,使用此类设置,如何测试 Configuration
类中定义的每个节点,以及它们的值是否已正确配置 .
The class to test
# My\Bundle\DependencyInjection\Configuration.php
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('my_bundle')
->children()
->scalarNode("scalar")->defaultValue("defaultValue")->end()
->arrayNode("arrayNode")
->children()
->scalarNode("val1")->defaultValue("defaultValue1")->end()
->scalarNode("val2")->defaultValue("defaultValue2")->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
以下是我想在单元测试中做的断言:
我试图以节点的形式访问节点,但它似乎不起作用 . 此外 TreeBuilder
似乎没有给我们将配置作为数组获取的可能性,除非它们由bundle扩展加载 .
Tests
# My\Bundle\Tests\DependencyInjection\ConfigurationTest.php
$configuration = $this->getConfiguration();
$treeBuilder = $configuration->getConfigTreeBuilder();
$this->assertInstanceOf("Symfony\Component\Config\Definition\Builder\TreeBuilder", $treeBuilder);
// How to access the treebuilder's nodes ?
$rootNode = $treeBuilder["my_bundle"];
$scalarNode = $treeBuilder["scalar"];
$arrayNode = $treeBuilder["arrayNode"];
$val1Node = $arrayNode["val1"];
$val2Node = $arrayNode["val2"];
$this->assertInstanceOf("Symfony\...\ArrayNodeDefinition", $rootNode);
$this->assertEquals("defaultValue", $scalarNode, "Test the default value of the node");
$this->assertEquals("defaultValue", $val1Node, "Test the default value of the node");
$this->assertEquals("defaultValue", $val2Node, "Test the default value of the node");
2 回答
我发现了一个可以在JMSSecurityBundle上运行的解决方案 .
我没有测试配置,而是测试扩展,这将为配置添加覆盖范围 . 这样,我可以断言已设置默认配置 .
例如,这是
Extension
.可以测试如下:
要测试您的配置 in isolation ,您可以这样做: