11

是否可以让子上下文类扩展另一个子上下文并覆盖函数?

目前我有

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作为子上下文。

当我运行测试时抱怨

[Behat\Behat\Exception\RedundantException]
步骤“/^a 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

3 回答 3

10

正如 Rob Squires 所提到的,动态上下文加载将不起作用。

但是我确实有一个解决方法来覆盖我经常使用的步骤定义。 不要注释你的方法。Behat 将获取超类中被覆盖方法的注释,并将该方法名称映射到匹配步骤。当找到匹配的步骤时,将调用子类中的方法。为了清楚起见,我已经为此使用了@override 注释。@override 注释对 Behat 没有特殊意义。

class SpecialTestContext extends TestContext {
    /**
     * @override Given /^a testScenarioExists$/
     */
    public function aTestscenarioexists() {
       echo "I am a special test scenario\n";
    }
}
于 2013-07-23T16:52:12.783 回答
4

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

在动态加载子上下文方面,这是不可能的:

  1. 子上下文在“编译时”加载 - 即。在主 FeatureContext 构造函数中
  2. 到第一个步骤定义运行时,behat 已经收集了所有注释并将它们映射到步骤定义,不能/不应该添加更多

检查一下以了解 a 的Context行为方式: http: //docs.behat.org/guides/4.context.html#contexts-lifetime

需要考虑的更广泛的事情:

  1. 在小黄瓜场景中捕获的任何内容都必须是非开发人员可以理解的,(或者至少是没有编写系统的开发人员!)。一个场景应该完整地传达一个(最好不要更多)业务规则,而无需深入研究任何代码

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

  3. 这取决于您如何组织 FeatureContexts,但是您希望通过系统中的主题/域来执行此操作,例如:

    • aDatabaseContext可能与读取 + 写入测试数据库有关
    • anApiContext可能包含与验证系统中的 api 有关的步骤
    • CommandContext可能与验证您的系统控制台命令有关
于 2013-04-08T23:36:31.863 回答
0

覆盖的方法不能用同一个句子定义。

class SpecialTestContext extends TestContext {

  public function aTestscenarioexists() {
    echo "I am a special test scenario\n";
  }
}
于 2013-09-18T19:31:59.673 回答