当没有工作时,Behat 3 + Symfony 3带有命名空间的上下文不起作用

时间:2016-11-15 12:28:50

标签: symfony autoload behat psr-4 psr-0

我有以下目录结构

composer.json
behat.yml
src
|--AppBundle
   |--Features
      |--example.feature
      |--Context
         |--FeatureContext.php

以下 behat.yml

default:
  autoload:
    '': 'src/AppBundle/Features/Context'
  suites:
    default:
      paths: ['src/AppBundle/Features']
      contexts:
        - FeatureContext:
          session: '@session'
    # and extensions standard for Symphony

FeatureContext.php 包含

<?php

//namespace AppBundle\Features\Context;

use Behat\Behat\Context\Context;
use Behat\MinkExtension\Context\MinkContext;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext implements Context
{   ...   }

有评论名称空间。当我运行behat时,现在正确找到了上下文。当我取消注释 namespace 时,会出现错误:

  

[贝哈特\贝哈特\语境\异常\ ContextNotFoundException]
  找不到FeatureContext上下文类,无法使用。

如果取消注释 FeatureContext.php 中的 namespace ,如何使其正常工作?我对PSR-0和PSR-4了解不多,但如果问题可以与我联系,我追加 composer.json 的片段。

"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},

我正在寻找编码的最佳实践,所以如果我做得不好,我会投票给出适当的建议。

  • 我似乎应该在 FeatureContext.php 中拥有 namespace ,不应该吗?
  • 我似乎不应该在 composer.json 中使用 PSR-0 ,我应该吗?

1 个答案:

答案 0 :(得分:2)

看看下面的例子。完整的示例如下:http://www.inanzzz.com/index.php/post/l41o/testing-a-basic-auth-symfony-api-with-behat3您还可以在此处找到更多相关示例:http://www.inanzzz.com/index.php/posts/behat

注1:您可以直接访问上下文文件中的session,因此无需注入。您可能需要使用implements KernelAwareContextimplements KernelAwareInterfaceimplements ContainerAwareInterface。只需查看上面的博文。

注意2:你根本不需要在composer.sjon中autoload-dev。摆脱它。

<强> composer.json

注意:使用新版本!

{
    "require-dev": {
        "behat/behat": "3.0.15",
        "behat/symfony2-extension": "2.1.0",
        "behat/mink": "1.7.0",
        "behat/mink-extension": "2.1.0",
        "behat/mink-browserkit-driver": "1.3.0"
    },
}

<强> behat.yml

default:
    extensions:
        Behat\Symfony2Extension: ~
        Behat\MinkExtension:
            base_url: http://your_local_app_domain.com/app_test.php/
            sessions:
                symfony2:
                    symfony2: ~
    suites:
        api:
            type: symfony_bundle
            bundle: ApplicationApiBundle
            mink_session: symfony2
            contexts:
                - Application\ApiBundle\Features\Context\FeatureContext:
                    param: 'whatever'

<强> FeatureContext.php

namespace Application\ApiBundle\Features\Context;

use Behat\MinkExtension\Context\MinkContext;

class FeatureContext extends MinkContext
{
    private $param;

    public function __construct($param)
    {
        $this->param = $param;
    }

    ......
}

<强>测试

$ bin/behat --suite=api @ApplicationApiBundle/YourFeature.feature
相关问题