2013-03-18 47 views
9

是否有可能让子上下文类扩展另一个子上下文并覆盖函数?是否可以覆盖behat上下文中的步骤定义?

目前我有

class TestContext extends BehatContext { 
    /** 
    * @Given /^a testScenarioExists$/ 
    */ 
    public function aTestscenarioexists() { 
     echo "I am a generic test scenario\n"; 
    } 
} 

class SpecialTestContext extends TestContext { 
    /** 
    * @Given /^a testScenarioExists$/ 
    */ 
    public function aTestscenarioexists() { 
     echo "I am a special test scenario\n"; 
    } 
} 

在功能方面,我告诉它我们SpecialTestContext作为子上下文。

当运行测试贝哈特与

抱怨[贝哈特\贝哈特\异常\ RedundantException]
步骤 “/ ^一个testScenarioExists $ /” 已经在SpecialTestContext定义:: aTestscenarioexists()

请问有人可以用这个指出我的正确方向吗?

给一些进一步的信息,为什么我试图做到这一点我想实现是运行与不同的环境场景的能力,并有小黄瓜文件中指定的环境中,例如:

Scenario: Test with generic environment 
Given I am in the environment "generic" 
    And a test scenario exists 

Scenario: Test with specialised environment 
Given I am in the environment "specialised" 
    And a test scenario exists 

然后我可以使用在FeatureContext中添加一些代码来加载正确的子上下文。

回答

4

总之......这是不可能的:http://docs.behat.org/guides/2.definitions.html#redundant-step-definitions

在装载子环境方面动态,这是不可能的:

  1. 子上下文是在“编译时”装 - 即。在主FeatureContext构造
  2. 通过第一步定义运行的时间,贝哈特已经收集了所有注解和映射他们的步骤定义,没有更多的可以/应该加入

检查了这一点,以了解如何一个Context的行为: http://docs.behat.org/guides/4.context.html#contexts-lifetime

夫妇的更广泛的事情要考虑:

  1. 在任何一个小黄瓜场景拍摄多亩非开发人员可以理解(或者至少是没有编写系统的开发人员!)。一个场景应该传达完整的,一个(理想情况下不多于)业务规则,而无需挖掘任何代码

  2. 您不想在步骤定义中隐藏太多逻辑,任何规则都应该在小黄瓜情景

  3. 这是给你的,你如何组织你的FeatureContexts,但你会希望通过主题/域系统内做到这一点,例如:

    • 一个DatabaseContext可以阅读关注+写入测试分区
    • ApiContext可能包含涉及您的系统
    • CommandContext内验证的API可以验证您的系统控制台有关步骤命令
+0

只是更新上面提供的链接。 * http://docs.behat.org/en/latest/user_guide/context/definitions.html#redundant-step-definitions * http://docs.behat.org/en/latest/user_guide/context。 html#contexts-lifetime – aczietlow 2017-08-24 17:07:26

9

正如罗布·斯夸尔斯所提到的,动力方面装载将无法正常工作。

但我确实有一个解决方法来覆盖步骤定义,我经常使用。 不要注释你的方法。 Behat将在超类中选取重写方法的注释,并将该方法名称映射到匹配步骤。当找到匹配步骤时,将调用子类中的方法。为了说明问题,我已经开始为此使用@override注释。 @override注释对Behat没有特殊意义。

class SpecialTestContext extends TestContext { 
    /** 
    * @override Given /^a testScenarioExists$/ 
    */ 
    public function aTestscenarioexists() { 
     echo "I am a special test scenario\n"; 
    } 
} 
+1

这是实际的解决方案 - 在子类中重写方法,而不更改模式docblock。 – 2014-03-28 12:56:31

0

无法用同一句子定义重写的方法。

class SpecialTestContext extends TestContext { 

    public function aTestscenarioexists() { 
    echo "I am a special test scenario\n"; 
    } 
} 
相关问题