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:

	public void login() throws Throwable{
	public void close_driver() throws Throwable {

@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:

	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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>