如何为Maven和Cucumber定义JUnit @Before钩子的不同行为

问题描述 投票:3回答:2

我的挑战是我有两种不同类型的测试,使用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
} 

但是,在非UI测试中,例如API测试,我不需要旋转这些浏览器。因此,我真的需要一个名为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)的适当逻辑?

java maven cucumber cucumber-jvm
2个回答
2
投票

您可以使用标记挂钩执行此操作:“可以根据场景的标记有条件地选择挂钩执行。要仅针对某些场景运行特定挂钩,您可以将挂钩与标记表达关联。”来自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的顺序。

© www.soinside.com 2019 - 2024. All rights reserved.