Friday, December 18, 2015

JVM Cucumber Hooks Part 1

As the name itself suggests hooks are used to hook any feature or scenario. In a simpler terms you can create a function and then hook that into any feature or scenario.

There are two types of hooks you can create.  Please not there ain't such categories, I have just divided them into following categories for better understanding.
  • Generic Hooks:  Hooks that executes before or after each and every scenario.
  • Specific Hooks: Hooks that executes before or after every specific(mentioned) scenario or feature. 

Now let's see how to implement this, for this I am going to use the same example I used in the last blog post. if you haven't read that yet, please visit it here. 

Generic Hooks

if you will check the code of the previous post, we were creating the driver object, in the class file as we had only one test case(scenario).  if we have multiple scenarios and we want to open new browser before each and every scenario and want to close after each and every scenario we can utilize the hooks.

In the following example, I am going to create a hook (setUp method) that will be called before each and every scenario. this method will open a firefox browser and will navigate to site home page. I will also create an another hook (tearDown method) which will be called after each and every scenario. This method will close the browser after each and every scenario.

Hooks.java
public class Hooks extends WebDriverManager{

    @Before
    public void setUp(){
        driver = new FirefoxDriver();
        wait = new WebDriverWait(driver, 30);
        driver.get("https://en.wikipedia.org");
        driver.manage().window().maximize();
    }

    @After
    public void tearDown(){
        driver.quit();
    }
}

WebDriverManager.java
public class WebDriverManager {
    public static WebDriver driver;
    public static WebDriverWait wait;
}

HomePage.java
public class HomePage extends WebDriverManager{
 
    @When("^I search \"(.*?)\"$")
    public void i_search(String arg1) throws Throwable {
        WebElement search_box = driver.findElement(By.id("searchInput"));
        search_box.sendKeys(arg1);
        search_box.submit();
    }

    @Then("^I should get \"(.*?)\" on page$")
    public void i_should_get_on_page(String arg1) throws Throwable {
        Assert.assertTrue(driver.findElement(By.xpath("//body")).getText().contains(arg1));
    }
}

wkipedia_search.feature
@Search
Feature: Verify WikiPedia Search

  @Regression @Functional
  Scenario: Verify Wikipdia for indirect posts-BDD
  When I search "BDD"
  Then I should get "Behavior-driven development" on page

  @Regression
  Scenario: Verify Wikipdia for indirect posts-TDD
  When I search "TDD"
  Then I should get "Test-driven development" on page