How to define different behavior for JUnit @Before hook with Maven and Cucumber

Nikolay Advolodkin :

My challenge is that I have two different types of tests that run using Cucumber BDD with Java, Maven, and JUnit.

In several features, related to the UI, I need to perform some actions before every single scenario such as spinning up VMs, like this:

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

However, in non-UI tests, such as API tests, I don't need those browsers to be spun up. Hence, I really need a different behavior for the @Before method called setUp.

The challenge that I am facing is that it seems as though the @Before hook works for every single test method, even if these methods are in different classes. As a result, no matter what I try, the browser resources are always created, even for API tests that don't need the browsers.

Here is what I've tried without success:

  • I created a totally separate feature file and StepDefinitions file for the API tests. The definitions file has no reference to @Before method. However, the @Before from the UI tests step definitions still gets executed for the API features. Here's an example of how I separated the files( before, I had them in the exact same package even though the image is showing in different packages): https://screencast.com/t/ht5Jz4cLC

    • I tried to create new packages for the types of tests such as .api and .ui. This works when I run through IntelliJ, but doesn't work when I execute "mvn test". Seems that no tests are found or executed. Here is how this setup looks: https://screencast.com/t/uSlB4sYTFm

    • I tried to set a static property in one of my test methods that would decide if I have an API test and then update implementation in setUp() based on that. This of course didn't work because setUp() gets executed before the actual test that knows if it's a UI or API test.

Is there a way to change the behavior of setUp in an automated way so that it executes/doesn't execute the appropriate logic based on the test type (API/UI)?

Marit :

You can use tagged hooks to do this: "Hooks can be conditionally selected for execution based on the tags of the scenario. To run a particular hook only for certain scenarios, you can associate a Hook with a tag expression." from the docs.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92672&siteId=1