【问题标题】:How to inject a service into Behat feature context in Slim 4 framework如何在 Slim 4 框架中将服务注入 Behat 特征上下文
【发布时间】:2019-12-03 15:29:02
【问题描述】:

当我搜索服务注入功能上下文时,我总是会找到 symfony 的扩展。但我需要扩展或其他东西才能在 Slim 4 框架中执行此操作。

谢谢。

【问题讨论】:

    标签: bdd slim behat slim-4


    【解决方案1】:

    我使用 trait 解决了这个问题。

        // src/Application/Utility/ContainerInjection.php
    
        use DI\Container;
        use DI\ContainerBuilder;
    
        trait ContainerInjection
        {
            /**
             * @return Container
             */
            public function getContainer()
            {
                // To find project base path 
                // according to path where trait is found
                $path_main = __DIR__ . '/../../../';
    
                // Instantiate PHP-DI ContainerBuilder
                $containerBuilder = new ContainerBuilder();
    
                $settings = require $path_main . 'app/settings.php';
                $dependencies = require $path_main . 'app/dependencies.php';
    
                $settings($containerBuilder);
                $dependencies($containerBuilder);
    
                // Build PHP-DI Container instance
                return $containerBuilder->build();
            }
        }
    

    在 FeatureContext 中使用这个特性

        class FeatureContext implements Context
        {
            use ContainerInjection;
    
            private $myService;
    
            public function __construct()
            {
                $container = $this->getContainer();
                $this->myService = $container->get(MyService::class);
            }
         }
    

    【讨论】:

    • 您是否能够运行 REST 测试而不执行实际的 HTTP 请求,但在 Slim4 中运行内部请求/响应?
    • 我正在使用 Slim\Http\Request 和 Slim\Http\Response 运行 api 测试。但我不确定我是否理解正确。如果你能描述得更详细一点,我可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2016-06-29
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多