【问题标题】:How to define different behavior for JUnit @Before hook with Maven and Cucumber如何使用 Maven 和 Cucumber 为 JUnit @Before 挂钩定义不同的行为
【发布时间】:2019-03-11 22:21:04
【问题描述】:

我的挑战是我有两种不同类型的测试,它们使用 Cucumber BDD 和 Java、Maven 和 JUnit 运行。

在与 UI 相关的几个功能中,我需要在每个场景之前执行一些操作,例如启动 VM,如下所示:

public class StepDefinitions {
    @Before
    protected void setUp(Scenario scenario) throws MalformedURLException {
        //Create browser resources here for all of my UI related scenarios
} 

但是,在 API 测试等非 UI 测试中,我不需要启动这些浏览器。因此,对于名为 setUp 的 @Before 方法,我确实需要一种不同的行为。

我面临的挑战是@Before 钩子似乎适用于每个测试方法,即使这些方法位于不同的类中。结果,无论我尝试什么,总是会创建浏览器资源,即使对于不需要浏览器的 API 测试也是如此。

这是我尝试过但没有成功的方法:

  • 我为 API 测试创建了一个完全独立的功能文件和 StepDefinitions 文件。定义文件没有引用 @Before 方法。但是,UI 测试步骤定义中的 @Before 仍会针对 API 功能执行。这是我如何分离文件的示例(之前,我将它们放在完全相同的包中,即使图像显示在不同的包中):https://screencast.com/t/ht5Jz4cLC

    • 我尝试为 .api 和 .ui 等测试类型创建新包。这在我通过 IntelliJ 运行时有效,但在我执行“mvn test”时不起作用。似乎没有找到或执行任何测试。以下是此设置的外观:https://screencast.com/t/uSlB4sYTFm

    • 我尝试在我的一个测试方法中设置一个静态属性,该属性将决定我是否进行 API 测试,然后基于此更新 setUp() 中的实现。这当然行不通,因为 setUp() 在知道是 UI 还是 API 测试的实际测试之前执行。

有没有办法以自动方式更改 setUp 的行为,以便它根据测试类型(API/UI)执行/不执行适当的逻辑?

【问题讨论】:

  • 我建议使用qaf,而不是由框架负责驱动程序管理。您可以使用内置的web-service automation support 进行 API/UI 编排。如果您有现有项目,您可以轻松migrate 到 qaf。
  • 你可以尝试使用标签进行 UI 测试,并在 Before 挂钩中使用相同的标签。使用标签选项具有相同值的运行器运行它们。对于 API 测试,您可以使用“not @ui”作为跑步者的标记值。

标签: java maven cucumber cucumber-jvm


【解决方案1】:

您可以使用标记的挂钩来执行此操作: “可以根据场景的标签有条件地选择执行挂钩。要仅针对某些场景运行特定的挂钩,您可以将挂钩与标签表达式相关联。”来自docs

【讨论】:

    【解决方案2】:
    Feature File :- Hainvg 2 Scenarios, one for UI and other one for API
    
    @UI
    Scenario: This is First UI Scenario running on chrome browser
     Given this is the first step
     When this is the second step
     Then this is the third step
    
    @Non-UI 
    Scenario: This is First Non-UI Scenario running on chrome browser
     Given this is the first step
     When this is the second step
     Then this is the third step
    
     ------------------------------------------ Hook Implementation ------------------------------------------
    @Before("@UI")
        public void beforeUISetup(){
           Do here :- In several features, related to the UI, I need to perform some actions before every single scenario such as spinning up VMs
        } 
    
    @Before("@Non-UI")
        public void beforeNon-UIScenario(){
         Do here :- in non-UI tests, such as API tests, I don't need those browsers to be spun up
        } 
    

    如果您需要先运行非 UI 的 @Before 方法,那么我们也可以设置这些 @Before 的顺序。

    【讨论】:

      猜你喜欢
      • 2014-02-09
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2019-03-30
      相关资源
      最近更新 更多