7. Hooks

Cucumber provides a methodology called Hooks which is analogue to traditional before and after methods. The hooks must be annotated with @Before and @After in step classes. Make sure to use cucumber.api.java.Before and cucumber.api.java.After annotations and not the JUnit ones. By default each before method will be executed before all scenarios and each after method will be executed after all scenarios. If a hook needs to be executed only for a particular scenario, then we need to use tags. To tag a before method, we need to insert a string parameter to the annotation. To bind the tagged hook to a particular scenario we need to “annotate” the scenario with the same string tag. Here is an example:

@Before("@login")
	public void login() throws Throwable{
		openDriver();
		System.out.println("login()");
		testSteps.user_is_on_Home_Page();
		testSteps.user_Navigate_to_LogIn_Page();
		testSteps.user_enters_UserName("Tester843");
		testSteps.user_enters_Password("x%kzJwbsW1)AIB2k");
		testSteps.click_login();
		testSteps.message_displayed_Login_Successfully();
	}
@After("@close")
	public void close_driver() throws Throwable {
		System.out.println("close_driver()");
		baseObject.driver.close();
	}

@login @close
 Scenario: Successful LogOut
    When User LogOut from the Application
    Then Message displayed LogOut Successfully

Cucumber allows to create a scenario which is tagged with a hook but doesn’t contains any real test step. For instance:

@login
	@logout
	Scenario: Successful Login and Logout

Cucumber also allows to tag a scenario with multiple before and after methods. The execution order of the hooks is not defined, which means the same test can be executed in different ways which leads us to different results.

This is not totally ideal for web testing. Without Cucumber we had a TestBase where we was able to solve the initialization and the termination of webdriver for all test cases. Now we need to solve it in test steps with hooks, but we cannot be sure in which order will be the hooks executed. To make sure about the initialization order of the hooks, we need to implement only one before and after hook. The ordinary before hook should initialize the driver and the ordinary after hook should terminate it.

Similar Posts from the author: