What is Hook in Cucumber?In Cucumber, the hook is the block of code which can be defined with each scenario in step definition file by using the annotation @Before and @After. These @Before and @After annotations create a block in which we can write the code. Cucumber hook facilitates us to handle the code workflow better and also helps us to reduce code redundancy. Syntax: As per the code logic, hook's job is to start and close the web driver session after a specific function/method. Hence, in actual, it is not relevant to any function/method or scenario. Note: Hooks can be defined only in the step definition file.The Need of HookAt the time of testing, we may encounter circumstances where we need to perform some conventional prerequisite steps before the testing of the test scenario. Consider the following prerequisite to understand the kind of prerequisites which may encounter at the time of testing:
Similarly, there are always some prerequisite steps which may encounter after testing:
In order to handle these types of conventional prerequisite steps, using cucumber hook is the best option. Hook AnnotationsUnlike TestNG Annotations, the cucumber supports only two hooks:
@Before As the name suggests, we can use the @Before hook with the function/method after which we need to start web driver. @After As the name suggests, we can use the @After hook with the function/method after which we need to close the web driver. Let's understand this notion better with an example of a step definition file. Example:Here is an instance of a step definition file of a Maven testing project. This project is created for the testing of web application javaTpoint. In order to use the hook, we created the step definition file named hookTest.java under the package javatpointTest. When we execute this code, the following will be the sequence of execution:
Since we know that, to execute step definition file, we should have a complete Maven testing project so first create it in eclipse. Tagged HooksThe hook can also we used with tag. We can use @before and @after hooks with a specific test. Example: We can also use the same concept of the hook with logical and/or operator. Example: Next Topic# |