Вы находитесь на странице: 1из 42

Cucumber with Selenium

MOHAN SEERANGAN
25/04/18
Contents
Cucumber Introduction:..................................................................................................................................... 4
Benefits of TDD .................................................................................................................................................. 4
Drawbacks of TDD .............................................................................................................................................. 4
Best BDD Tools and Testing Frameworks .......................................................................................................... 5
Features of Cucumber........................................................................................................................................ 5
Cucumber KEYWORDS ....................................................................................................................................... 6
Cucumber Design ............................................................................................................................................... 6
What is "Feature File"? ...................................................................................................................................... 6
What is "Step Definition" ................................................................................................................................... 6
Cucumber - Annotations .................................................................................................................................... 7
Create cucumber feature file ............................................................................................................................. 7
Steps to Configure Cucumber Eclipse Plugin ................................................................................................... 10
Structure that will be followed for Cucumber ................................................................................................. 12
Some important points about Cucumber feature file ..................................................................................... 12
What’s next? .................................................................................................................................................... 13
Create Cucumber Test Runner class ................................................................................................................ 13
What is Cucumber Test Runner Class? ............................................................................................................ 13
Add Cucumber Test Runner class to Eclipse project ........................................................................................ 13
Add code to test runner class .......................................................................................................................... 14
Understanding the annotations in the test runner class ................................................................................. 14
How to create Cucumber Step Definition class ............................................................................................... 15
What is Cucumber step definition class? ......................................................................................................... 15
Identify the step definition methods to be added........................................................................................... 15
Create new step definition class ...................................................................................................................... 16
Add step definition methods to the class ........................................................................................................ 16
Run cucumber test runner class once again .................................................................................................... 18
Add Selenium code in Step Definition class ..................................................................................................... 19
Which approach to be used to write selenium code? ..................................................................................... 19
Create new java class to add Cucumber Selenium code ................................................................................. 19
What are Hooks in Cucumber? ........................................................................................................................ 20
Why Cucumber Hooks?.................................................................................................................................... 20

Cucumber for Selenium Page 2


How to implement Hooks in Cucumber Test ................................................................................................... 20
2. Test Hooks with Multiple Scenarios ..................................................................................................... 22
Test Hooks with Example Scenarios ......................................................................................................... 23
Project Exercise ................................................................................................................................................ 24
Exercise -1 ................................................................................................................................................ 24
Exercise -2 ................................................................................................................................................ 26
Exercise -3 ................................................................................................................................................ 28
Exercise -4 ................................................................................................................................................ 30
Exercise -5 ................................................................................................................................................ 32
Exercise -6 ................................................................................................................................................ 33
Exercise -7 ................................................................................................................................................ 35
Exercise -8 ................................................................................................................................................ 37
Exercise -9 ................................................................................................................................................ 39
Project: Page Object Model with Cucumber: .................................................................................................. 41

Cucumber for Selenium Page 3


Cucumber:
Cucumber is a software tool used by computer programmers for testing other software. It
runs automated acceptance tests written in a behavior-driven development (BDD) style. Central to
the Cucumber BDD approach is its plain language parser called Gherkin. ... Cucumber is written in the Ruby
programming language.

Cucumber Introduction:
A cucumber is a tool based on Behavior Driven Development (BDD) framework which is used to
write acceptance tests for the web application. It allows automation of functional validation in easily
readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.

Cucumber feature files can serve as a good document for all. There are many other tools like JBehave which
also support BDD framework. Initially, Cucumber was implemented in Ruby and then extended to Java
framework. Both the tools support native JUnit.(it only support JUnit and it doesn't support TestNG)

Behavior Driven Development is an extension of Test Driven Development and it is used to test the system
rather than testing the particular piece of code. We will discuss more the BDD and style of writing BDD
tests.

Cucumber can be used along with Selenium, Watir, and Capybara etc. Cucumber supports many other
languages like Perl, PHP, Python, Net etc. In this tutorial, we will concentrate on Cucumber with Java as a
language.

Test driven development(TDD)


TDD is a technique of using automated unit tests to drive the design of software and force
decoupling of dependencies. The result of using this practice is a comprehensive suite of unit tests that can
be run at any time to provide feedback that the software is still working.

The concept is to “get something working now and perfect it later.” After each test, refactoring is done and
then the same or a similar test is performed again. The process is iterated as many times as necessary until
each unit is functioning according to the desired specifications.

Benefits of TDD
 Unit test proves that the code actually works
 Can drive the design of the program
 Refactoring allow to improve the design of the code
 Low Level regression test suite
 Test first reduce the cost of the bugs

Drawbacks of TDD
 Developer can consider it as a waste of time

Cucumber for Selenium Page 4


 The test can be targeted on verification of classes and methods and not on what the code really
should do
 Test become part of the maintenance overhead of a project
 Rewrite the test when requirements change

Acceptance Test Driven Development(ATDD)


It is also less commonly designated as Story test Driven Development (STDD). It is a technique used
to bring customers into the test design process before coding has begun. It is a collaborative practice where
users, testers, and developers define automated acceptance criteria. ATDD helps to ensure that all project
members understand precisely what needs to be done and implemented. Failing tests provide quick
feedback that the requirements are not being met. The tests are specified in business domain terms. Each
feature must deliver real and measurable business value: indeed, if your feature doesn’t trace back to at
least one business goal, then you should be wondering why you are implementing it in the first place.

Behaviour driven development(BDD)


In BDD on the other hand, the tests are described in a natural language, which makes the tests
more accessible to people outside of development or testing teams. It can describe the functionality as
specifications do.

Best BDD Tools and Testing Frameworks


Java framework: 6. BeanSpec
1. Cucumber 7. Easy B
2. JBehave
3. JDave .Net Framework:
4. Fitnesse 8. SpecFlow
5. Concordion

Features of Cucumber
1. First point and the most important is the price. And, yes! It is free to use
2. Cucumber helps in writing the tests which are easy to understand by anyone irrespective of the
Technical knowledge they possess
3. The stakeholders, Business Owners, Testers and Developers work on the problem statement to
derive the best behavior set
4. The behavior sets are then changed into Acceptance Test conditions using Cucumber
5. Cucumber as a tool maintains both the requirement statement and the Test conditions in the same
place
6. The tracking of the implementation is easy using Cucumber. The behavior set that is implemented
and working are displayed as working in Cucumber. The ones those are not are displayed
accordingly
7. Cucumber typically uses Ruby as the programming language. However, other languages such as
JAVA, Groovy etc. can also be used
8. Both the Testing team and development team are involved in writing/developing test conditions
9. Just like Selenium, Cucumber is restricted only for Web-based automation

Cucumber for Selenium Page 5


10. To use Cucumber, things such as Cucumber, IDE, Ansicon, Watir, RSpec should be installed. We
have already discussed that Cucumber uses Ruby as the programming language. Ruby and Ruby
development Kit should also be installed.

Cucumber KEYWORDS
 Feature
 Background  Then  Scenario Outline
 Scenario  And  Examples
 Given  But
 When  *

Cucumber Design

What is "Feature File"?


Feature File consist of following components -

 Feature: A feature would describe the current test script which has to be executed.
 Scenario: Scenario describes the steps and expected outcome for a particular test case.
 Scenario Outline: Same scenario can be executed for multiple sets of data using scenario outline.
The data is provided by a tabular structure separated by (I I).
 Background: Often times when writing multiple scenarios within a singular feature file you see repeated test
steps. Initial test steps that are common across all scenarios and scenario outlines can be pulled out into a
Background test step. These steps get executed before every scenario. This can greatly reduce the number of
test steps in the feature file, and increase readability.
 Given: It specifies the context of the text to be executed. By using data tables "Given", step can
also be parameterized. (Pre-Condition)
 When: "When" specifies the test action that has to performed (Test Condition)
 Then & But: The expected outcome of the test can be represented by "Then"(Expected Results)

What is "Step Definition"


Step definition maps the Test Case Steps in the feature files(introduced by Given/When/Then) to code. It
which executes the steps on Application Under Test and checks the outcomes against expected results. For
a step definition to be executed, it must match the given compoent in a feature. Step definition is defined
in ruby files under "features/step_definitions/*_steps.rb".

Cucumber for Selenium Page 6


Cucumber - Annotations
Annotation is a predefined text, which holds a specific meaning. It lets the compiler/interpreter know, what
should be done upon execution. Cucumber has got the following few annotations −

 Given − It describes the pre-requisite for the test to be executed.


Example − GIVEN I am a Facebook user

 When −It defines the trigger point for any test scenario execution.
Example − WHEN I enter "<username>"

 Then −Then holds the expected result for the test to be executed.
Example − THEN login should be successful.

 And −It provides the logical AND condition between any two statements. AND can be used in
conjunction with GIVEN, WHEN and THEN statement.
Example − WHEN I enter my "<username>" AND I enter my "<password>"

 But −It signifies logical OR condition between any two statements. OR can be used in conjunction
with GIVEN, WHEN and THEN statement.
Example − THEN login should be successful. BUT home page should not be missing.

 Scenario −Details about the scenario under the test needs to be captured after the keyword
“Scenario:”
Example −Scenario:
GIVEN I am a Facebook user
WHEN I enter my
AND I enter my
THEN login should be successful.
BUT home page should not be missing.
 Scenario Outline − (To be covered later)
 Examples − (To be covered later)

 Background −Background generally has the instruction on what to setup before each scenario runs.
However, it gets executed after “Before” hook (to be covered later). So this is ideal to be used for
code when we want to set up the web-browser or we want to establish the database connectivity.
Example −Background:
Go to Face book home page.

Create cucumber feature file


Follow the steps given below to first create a folder in your project and then add the feature file to it.
1. Right click on Cucumber Tutorial project, then select New > Source Folder.

Cucumber for Selenium Page 7


2. Enter folder name as resources and click on Finish button

3. You can now see that resources folder is added to your eclipse project. Now, right click
on resources folder and select New > Package

4. Enter package name as features and click on Finish button. This is the package inside which you will
add cucumber feature files

Cucumber for Selenium Page 8


5. We will now add cucumber feature file to this package. To do this, right click on features package
and select New > Other…

6. From the popup window, expand General folder and then select File option. Then click on Next
button

Cucumber for Selenium Page 9


7. Enter file name as GoogleHomepage.feature. Make sure that you add .feature at the end of the file
name. Now click on Finish button

You can now see that the cucumber feature file is added to the features package.

Steps to Configure Cucumber Eclipse Plugin


Installation of Cucumber Eclipse Plugin is easier, as it comes as a plugin for Eclipse IDE.

1. Launch the Eclipse IDE and from Help menu, click "Eclipse Marketplace" and type Cucumber
natural and finally search it

Cucumber for Selenium Page 10


2. Then Install "Natural 0.7.6" plugin and Select the Cucumber Eclipse Feature Option and click on
the Finish button. Then Select “I accept the terms of the license agreement” radio button and then
click on Finish button. Plugin installation will begin. You may or may not encounter a Security
warning, if in case you do just click OK. In case you encounter a security popup as below ,just click
on the OK button.
3. After successful installation of Cucumber plugin you will be ask to restart the Eclipse. Click on Yes
button.
4. Then Install "Cucumber Eclipse Plugin xxxxx" plugin and Select the Cucumber Eclipse Feature
Option and click on the Finish button. Then Select “I accept the terms of the license agreement”
radio button and then click on Finish button. Plugin installation will begin. You may or may not
encounter a Security warning, if in case you do just click OK. In case you encounter a security
popup as below ,just click on the OK button.
5. After successful installation of Cucumber plugin you will be ask to restart the Eclipse. Click on Yes
button.
6. Then check it pom.xml file, updated cucumber plugin else manually add the plugin in pom.xml file
to download automatically required setup.

Cucumber for Selenium Page 11


Structure that will be followed for Cucumber
Creating a cucumber test case with selenium is a multi-step process. On a high-level, it involves the
following steps –
 Identify the scenario you want to automate
 Add a feature file for the scenario that you identified
 Create a test runner class which will execute this feature file
 Create step definitions to link feature files with actual java code
 Write actual selenium logic and then link it with the step definition methods
Now, the structure that we will follow goes like this. We will first identify the scenario that we want to
automate. Then one by one, we will work on each of these cucumber components and build our test case
progressively. We will cover each component (feature file, test runner etc) in a separate article. So, by the
time you finish the next four articles, your first full-fledged cucumber test script will be ready.

Some important points about Cucumber feature file


Below are some of the important points that you need to be aware of w.r.t cucumber feature files –
 All feature files in Cucumber should have the extension .feature in its name. If .feature is not present,
then cucumber won’t recognize it as a feature file
 In each feature file, you need to add a keyword called ‘Feature’. Without this, you will see compile
errors in your script
 Each scenario in a feature file should also start with a keyword. We have used keyword ‘Scenario’ for
the feature file in this article. There is a different keyword as well, which we will discuss in detail in a
different article
 Each feature file can have multiple number of scenarios.
 It’s not necessary that all the scenarios have all these keywords – ‘given’, ‘when’, ‘then’ and ‘and’. You
can write scenarios where you can use only one keyword in all the steps. For example, the below
scenario which only uses Given keyword is perfectly valid

Cucumber for Selenium Page 12


Feature:
Scenario: Check that main elements on Google Homepage are displayed
Given I launch Chrome browser
Given I open Google Homepage
Given I verify that the page displays search text box
Given The page displays Google Search button
Given The page displays Im Feeling Lucky button

Apart from this, you can also change the order of the keywords. For example, you can use ‘and’ or ‘then’
before ‘given’ also. The only reason we use all given, when, then keywords is due to readability. And the
readability of a scenario is much better when you use these keywords in proper order.

What’s next?
You have now successfully created a feature file in your eclipse project. Cucumber understands
that you have provided a feature file, but it doesn’t know what to do with it. Cucumber won’t be able to
run this feature file unless you provide a runner class. We will work on creating a test runner class and link
it to this feature file. This will enable you to run the cucumber feature file.

Create Cucumber Test Runner class


With a cucumber-based framework, you cannot run a feature file on its own. You will need to create a java
class, which in turn will run this cucumber feature file. We call this class as cucumber test runner class.
Before we go ahead and add new test runner class, lets first have a quick look at cucumber test runner
class.

What is Cucumber Test Runner Class?


In very simple terms, Cucumber test runner class is one of the many mechanisms using which you can run
Cucumber feature file. The test runner class that will use in this article is a JUnit runner class. Below are
some of its salient features:
 In addition to running a cucumber feature file, the test runner class also acts as an interlink between
feature files and step definition classes. It is in test runner class, that you provide the path for both
feature file and step definition class
 There are multiple types of test runners such as JUnit runner, CLI runner, Android runner etc, that
you can use to run Cucumber feature file. Here will be using the JUnit runner
 With a test runner class, you have the option to run either a single feature file, or multiple feature
files as well. For now, we will focus on running a single feature file

Add Cucumber Test Runner class to Eclipse project


Follow the steps given below to add Cucumber test runner class to your Eclipse project:
1. First we need to have a new package where we will add the test runner class. To create this package,
right click on src folder and select New > Package
2. Give package name as testRunners and click on Finish button
3. The package will now be added to the project. Right click on the package and select New > Class
4. Give class name as TestRunner_GoogleHomepage and click on Finish button
Test runner class is now successfully added to your eclipse project. Let us now add code to the test runner
class.

Cucumber for Selenium Page 13


Add code to test runner class
We will just add the basic code that will help you run the cucumber feature file. At the basic level, you need
to add two annotations to your test runner class.

The complete code After you add the code, the test runner class should look something like this –

Before proceeding further, let us have a quick look at the annotations that you have used in the test runner
class. For cucumber test runner class (including the annotations) is given below. You can copy paste the
entire code to your runner class.

Understanding the annotations in the test runner class


You will see that our sample test runner class has only two annotations.
These are @RunWith and @CucumberOptions
1. @RunWith annotation: This is a JUnit annotation that specifies which runner it has to use to execute this
class. You can see that we have provided Cucumber.class as a parameter with this annotation. With this,
JUnit will know that it has to execute this test case as a Cucumber test.
2. @CucumberOptions annotation: This annotation provides some important information which will be
used to run your cucumber feature file. At the very least, Java should know the location of the feature file
as well as the step definition class in your project. CucumberOptions annotation will do just that. As of now,
we have provided two parameters in this annotation.
The first parameter, called features, provides the location of the feature file. Similarly, the second
parameter, called glue, provides the path of the step definition class.
We have currently stored the feature file in resources > features folder in the project. So, we have
added resources/features as the path for the feature file. Also, the glue parameter is empty, because we
have not created any step definitions class till now.

Cucumber for Selenium Page 14


It’s not that the @CucumberOptions annotation takes only these two parameters. There are few more
useful parameters which you can add here. With this, we finish our article on creating the basic cucumber
test runner class which will help you run the feature file. In our next article, we will run this test runner
class and then add the step definitions class as well.

How to create Cucumber Step Definition class


After you create this class, you will also add the step definition methods to it. Before we start creating step
definition class, let’s first get some basic understanding about it.

What is Cucumber step definition class?


Cucumber step definition class is a normal java class where you can store step definition methods.
And a step definition method is a java method that is linked to a step in the scenario in feature file. For
each scenario step in your feature file, you should add a step definition method. This way, all your steps
in feature files will have a method associated to it. So that, when you run the feature file, Cucumber would
execute the step definition methods linked with the steps.
Let us now identify the step definitions (also called as step defs) that you need to add in your project.

Identify the step definition methods to be added


One of the good things about Cucumber is that, it itself provides you the list of step definition
methods which you have not implemented yet. It also provides you with the syntax of these
methods. Let’s see the steps using which you can generate these step definition methods –
1. In Eclipse, open the test runner class, TestRunner_GoogleHomepage, which you created in the
previous
2. Right click anywhere inside the class and select Run As > JUnit Test
3. Once the test execution completes, you will see that Eclipse pops up console output window on the
screen. In this console output window, cucumber first displays this message – You can implement
missing steps with the snippets below.

Below this message, cucumber lists down all the step definition methods that you have to implement.

Cucumber for Selenium Page 15


This way, cucumber has itself generated the list of step defs that you have to implement. Also, it provides
you with the correct syntax of these methods. All that you have to do now is to copy paste these methods
to the step definition class.

Create new step definition class


In this section, we will create a new package and then add a new step definition class to it. The steps for
this are given below –
1. Right click on src folder and select New > Package
2. Give package name as stepDefinitions and click on Finish button
3. New package is now successfully added in src folder. Now, right click on this package and
select New > Class
4. Enter class name as StepDefs_GoogleHomepage and click on Finish button
With this, you have successfully created cucumber step definition class. Let us now add the step definition
methods to this class.

Add step definition methods to the class


Follow the steps given below to add step definition methods to the class –
1. Open the console window in Eclipse and copy all the methods that are given after “You can
implement missing steps with the snippets below:” line
2. Paste all these methods in StepDefs_GoogleHomepage class as shown below

Cucumber for Selenium Page 16


3. Add import statements for Given, When and Then. After this, delete the default comment and
throw new PendingException() statement from each step definition method. The code will now
look as in the below image. Please note that it doesn’t have any errors now

Cucumber for Selenium Page 17


With this, you have now implemented all the step definition methods at a basic level. As of now, these
methods are empty. This means that if you re-run the test runner class, you won’t see any message for
unimplemented steps as you saw previously.
Just so that we see some results when we run this test again, let us add print statements in each of these
methods. With this approach, when you run the scripts, there will be some text printed on the console. This
will show that the step definitions methods were executed.

4. Add System.out.println() method in each step definition method. The complete code will look like
this

Let us now re-run the test runner class and check that the step definition methods that you have added
work fine.

Run cucumber test runner class once again


Before we run the cucumber test runner once again, we need to add the path of the step definition class
in the test runner. Let’s do this first and then run the test runner class.
1. Open TestRunner_GoogleHomepage class
2. In glue keyword, add the package name of step definition class. Complete @CucumberOptions
annotation is given below

For better readability, you can split this in multiple lines as well The test runner class should look as shown
in the below image

Cucumber for Selenium Page 18


3. Now, right click inside this class and select Run As > JUnit Test
4. Once the test case execution completes, console view would be displayed. In the console view, you
can see that there is no message for missing implementation for steps. Instead, the console
displays all the statements that you had added in step definition methods. This means that the test
runner has executed all the step definition methods successfully.

We will end the article at this point, as you have completed creating a basic cucumber step definition
class. Even though this class is kind of empty, as it just prints out some statements on the console. But from
cucumber setup point of view, this is a big step.

Add Selenium code in Step Definition class


First add some selenium logic in our project and then we would integrate this code with the step
definition class.

Which approach to be used to write selenium code?


You can use any of the commonly used methods such as Page Object model, Page Factory model or any
other hybrid approach to write your selenium code. There’s just one important thing that you should be
careful about. Make sure that you keep Selenium and Cucumber implementation in separate classes. This
way your code will be much easier to understand and maintain.

Create new java class to add Cucumber Selenium code


1. We will first create a new package. To do this, right click on src folder and select New > Package
2. Give package name as seleniumPages and click on Finish button

Cucumber for Selenium Page 19


3. New package would be successfully added in src folder. Now, right click on this package and
select New > Class
4. Enter class name as Page_GoogleHomepage and click on Finish button

What are Hooks in Cucumber?


Cucumber supports hooks, which are blocks of code that run before or after each scenario. You can
define them anywhere in your project or step definition layers, using the
methods @Before and @After. Cucumber Hooks allows us to better manage the code workflow and helps
us to reduce the code redundancy. We can say that it is an unseen step, which allows us to perform our
scenarios or tests.

Why Cucumber Hooks?


In the world of testing, you must have encountered the situations where you need to perform the
prerequisite steps before testing any test scenario. This prerequisite can be anything from:
 Starting a webdriver
 Setting up DB connections
 Setting up test data
 Setting up browser cookies
 Navigating to certain page
 or anything before the test
In the same way there are always after steps as well of the tests like:
 Killing the webdriver
 Closing DB connections
 Clearing the test data
 Clearing browser cookies
 Logging out from the application
 Printing reports or logs
 Taking screenshots on error
 or anything after the test

To handle these kind of situations, cucumber hooks are the best choice to use. Unlike TestNG Annotaions,
cucumber supports only two hooks (Before & After) which works at the start and the end of the test
scenario. As the name suggests, @before hook gets executed well before any other test scenario,
and @after hook gets executed after executing the scenario.

How to implement Hooks in Cucumber Test


Let’s do some easy and small example of Cucumber Hooks just to understand the concept. I will bring the
intelligent usage of Hooks in my later tutorial series of Designing Framework with Cucumber.

1. Test Hooks with Single Scenario

Cucumber for Selenium Page 20


Note: There is no logic used in the step definitions. Just printing the step summary log.

Cucumber for Selenium Page 21


Things to note
 An important thing to note about the after hook is that even in case of test fail, after hook will
execute for sure.
 Method name can be anything, need not to be beforeScenario() or afterScenario(). can also be
named as setUp() and tearDown().
 Make sure that the package import statement should be import cucumber.api.java.After; & import
cucumber.api.java.Before;
Often people mistaken and import Junit Annotations, so be careful with this.

Output

No need of explanation, it is self explanatory

2. Test Hooks with Multiple Scenarios


I just wanted to show you the reaction of Hooks with the multiple scenarios. Let’s just add one more Test
Scenario in the feature file and run the feature again.

Note: Scenario Hooks execute before and after every scenario. In the above example, executed two times
for two scenarios.

Cucumber for Selenium Page 22


Test Hooks with Example Scenarios
Lets take a look when we have Scenario Outline with Examples.

Note: Again, in cucumber every example is considered as a separate scenario. So the output is same as the
second example above.

Cucumber for Selenium Page 23


Project Exercise

Exercise -1
Single scenario in feature file with single test definition:
Bussiness_Scenarios_01.feature
Feature: Example Scenarios

# Scenario-1
Scenario: Login for leaftaps positive

Given Open the browser_sc1


And Launch the url_sc1
And set timeout_sc1
And Maximize the browser_sc1
And Enter User Name_sc1
And Enter Password_sc1
When Click on Login button_sc1
Then Verify login is sucessful_sc1
When Close the driver_sc1

a. TestRunner_01.java

Cucumber for Selenium Page 24


package cucumber_TestCases_01;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/java/feature/Bussiness_Scenarios_01.feature",
glue = "cucumber_TestCases_01")
public class TestRunner_01 {

b. CucumberTestCase_01.java
package cucumber_TestCases_01;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_01 {

public static ChromeDriver driver;

@Given("Open the browser_sc1")


public void Browser() {
System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
}

@And("Launch the url_sc1")


public void Launchurl() {
driver.get("http://leaftaps.com/opentaps/control/main");
}

@And("set timeout_sc1")
public void Timeout() {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}

@And("Maximize the browser_sc1")


public void Maximize() {
driver.manage().window().maximize();
}

@And("Enter User Name_sc1")


public void UserName() {
driver.findElementById("username").sendKeys("DemoSalesManager");
}

Cucumber for Selenium Page 25


@And("Enter Password_sc1")
public void Password() {
driver.findElementById("password").sendKeys("crmsfa");
}

@When("Click on Login button_sc1")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc1")


public void Verify() {
System.out.println("Login Successful");
}

@When("Close the driver_sc1")


public void Close() {
driver.quit();
}
}

Exercise -2
Multiple scenarios in one feature file with test definitions (with background for common steps):
a. Bussiness_Scenarios_02.feature
Feature: Example Scenarios
# Scenario-4
Background: User is login leaftaps
Given Open the browser_sc4
And Launch the url_sc4
And set timeout_sc4
And Maximize the browser_sc4

Scenario: Login for leaftaps with login 01


And Enter User Name_sc4_1 as DemoSalesManager
And Enter Password_sc4_1 as crmsfa
When Click on Login button_sc4_1
Then Verify login is sucessful_sc4_1
When Close the driver_sc4_1

Scenario: Login for leaftaps with login 02


And Enter User Name_sc4_2 as DemoCSR
And Enter Password_sc4_2 as crmsfa
When Click on Login button_sc4_2
Then Verify login is sucessful_sc4_2
When Close the driver_sc4_2

b. TestRunner_04.java
package cucumber_TestCases_04;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

Cucumber for Selenium Page 26


@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/java/feature/Bussiness_Scenarios_02.feature",
glue = "cucumber_TestCases_04")
public class TestRunner_04 {
}

c. CucumberTestCase_04.java
package cucumber_TestCases_04;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_04 {

public static ChromeDriver driver;

@Given("Open the browser_sc4")


public void Browser() {
System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
}

@And("Launch the url_sc4")


public void Launchurl() {
driver.get("http://leaftaps.com/opentaps/control/main");
}

@And("set timeout_sc4")
public void Timeout() {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}

@And("Maximize the browser_sc4")


public void Maximize() {
driver.manage().window().maximize();
}

@And("Enter User Name_sc4_1 as (.*)")


public void UserName1(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc4_1 as (.*)")


public void Password1(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc4_1")

Cucumber for Selenium Page 27


public void LoginBtn1() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc4_1")


public void Verify11() {
System.out.println("Login Successful");
}

@When("Close the driver_sc4_1")


public void Close1() {
driver.quit();
}

@And("Enter User Name_sc4_2 as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc4_2 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc4_2")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc4_2")


public void Verify2() {
System.out.println("Login Successful");
}

@When("Close the driver_sc4_2")


public void Close() {
driver.quit();
}
}

Exercise -3
Command line in feature file:
a. Bussiness_Scenarios_03.feature
Feature: Example Scenarios

# Scenario-5
# Given Open the browser_sc1
# And Launch the url_sc1
# And set timeout_sc1
# And Maximize the browser_sc1

Scenario: Login for leaftaps with before and after


And Enter User Name_sc5 as DemoSalesManager

Cucumber for Selenium Page 28


And Enter Password_sc5 as crmsfa
When Click on Login button_sc5
Then Verify login is sucessful_sc5

# When Close the driver_sc5

b. TestRunner_05.java
package cucumber_TestCases_05;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/java/feature/Bussiness_Scenarios_03.feature",
glue = "cucumber_TestCases_05")
public class TestRunner_05 {

c. CucumberTestCase_05.java
package cucumber_TestCases_05;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_05 {

public static ChromeDriver driver;

@Before
public void beforeScenario() {
System.out.println("This will run before the Scenario");
System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario() {
System.out.println("This will run after the Scenario");
driver.quit();
}

Cucumber for Selenium Page 29


@And("Enter User Name_sc5 as (.*)")
public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc5 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc5")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc5")


public void Verify() {
System.out.println("Login Successful");
}
}

Exercise -4
Single scenarios with same steps repeated in feature file with different test data (one step definition):
a. Bussiness_Scenarios_04.feature
Feature: Example Scenarios

# Scenario-6
Scenario: Login for leaftaps01
And Enter User Name as DemoSalesManager
And Enter Password as crmsfa
When Click on Login button
Then Verify login is sucessful

Scenario: Login for leaftaps02


And Enter User Name as DemoCSR
And Enter Password as crmsfa
When Click on Login button
Then Verify login is sucessful

b. TestRunner_06.java
package cucumber_TestCases_06;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/java/feature/Bussiness_Scenarios_04.feature",
glue = "cucumber_TestCases_06")
public class TestRunner_06 {

Cucumber for Selenium Page 30


c. CucumberTestCase_06.java
package cucumber_TestCases_06;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.Scenario; //Added Cucumber API


import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_06 {

public static ChromeDriver driver;

@Before
public void beforeScenario(Scenario sc) throws Exception{
System.out.println("Starting executig scenario " + sc.getName());

System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario(Scenario sc) {
System.out.println("Completing scenario " + sc.getName());

System.out.println("This will run after the Scenario");


driver.quit();
}

@And("Enter User Name as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful")


public void Verify() {

Cucumber for Selenium Page 31


System.out.println("Login Successful");
}
}

Exercise -5
Multiple Test data provided in feature file (with examples):
a. Bussiness_Scenarios_05.feature
Feature: Example Scenarios

# Scenario-7
Scenario: Login for leaftaps01

And Enter User Name_sc7 as DemoSalesManager


And Enter Password_sc7 as crmsfa
When Click on Login button_sc7
Then Verify login is sucessful_sc7

Scenario Outline: Login for leaftaps02

And Enter User Name_sc7 as <uName> #added variable name and mention
examples multiple data
And Enter Password_sc7 as <password>
When Click on Login button_sc7
Then Verify login is sucessful_sc7
Examples:
|uName|password|
|DemoSalesManager|crmsfa|
|DemoCSR|crmsfa|

b. TestRunner_07.java
package cucumber_TestCases_07;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/java/feature/Bussiness_Scenarios_05.feature",
glue = "cucumber_TestCases_07")
public class TestRunner_07 {
}

c. CucumberTestCase_07.java
package cucumber_TestCases_07;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.Scenario; //Added Cucumber API


import cucumber.api.java.After;
import cucumber.api.java.Before;

Cucumber for Selenium Page 32


import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_07 {

public static ChromeDriver driver;

@Before
public void beforeScenario(Scenario sc) throws Exception{
System.out.println("Starting executig scenario " + sc.getName());

System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario(Scenario sc) {
System.out.println("Completing scenario " + sc.getName());

System.out.println("This will run after the Scenario");


driver.quit();
}

@And("Enter User Name_sc7 as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc7 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc7")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc7")


public void Verify() {
System.out.println("Login Successful");
}
}

Exercise -6
Groping in feature and step definition files with different test data:
a. Bussiness_Scenarios_06.feature
Feature: Example Scenarios

Cucumber for Selenium Page 33


# Scenario-8
@Smoke @Regression
Scenario: Login for leaftaps01

And Enter User Name_sc8 as DemoSalesManager


And Enter Password_sc8 as crmsfa
When Click on Login button_sc8
Then Verify login is sucessful_sc8

@Regression
Scenario Outline: Login for leaftaps02

And Enter User Name_sc8 as <uName> #added variable name and mention
examples multiple data
And Enter Password_sc8 as <password>
When Click on Login button_sc8
Then Verify login is sucessful_sc8
Examples:
|uName|password|
|DemoSalesManager|crmsfa|
|DemoCSR|crmsfa|

b. TestRunner_08.java
package cucumber_TestCases_08;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions( features =
"src/main/java/feature/Bussiness_Scenarios_06.feature",
glue = "cucumber_TestCases_08",
tags= {"@Smoke"}
) //Grouping with Feature file Examples- @Sanity,
@Smoke, @Regression etc.
public class TestRunner_08 {

c. CucumberTestCase_08.java
package cucumber_TestCases_08;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.Scenario; //Added Cucumber API


import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

Cucumber for Selenium Page 34


public class CucumberTestCase_08 {

public static ChromeDriver driver;

@Before
public void beforeScenario(Scenario sc) throws Exception{
System.out.println("Starting executig scenario " + sc.getName());

System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario(Scenario sc) {
System.out.println("Completing scenario " + sc.getName());

System.out.println("This will run after the Scenario");


driver.quit();
}

@And("Enter User Name_sc8 as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc8 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc8")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc8")


public void Verify() {
System.out.println("Login Successful");
}
}

Exercise -7
Multiple Grouping in single scenario in feature file with step definition: (Tags: any one condition execute)

a. Bussiness_Scenarios_07.feature
Feature: Example Scenarios

# Scenario-9
@Smoke @Regression
Scenario: Login for leaftaps01

Cucumber for Selenium Page 35


And Enter User Name_sc9 as DemoSalesManager
And Enter Password_sc9 as crmsfa
When Click on Login button_sc9
Then Verify login is sucessful_sc9

@Sanity @Regression
Scenario Outline: Login for leaftaps02

And Enter User Name_sc9 as <uName> #added variable name and mention
examples multiple data
And Enter Password_sc9 as <password>
When Click on Login button_sc9
Then Verify login is sucessful_sc9
Examples:
|uName|password|
|DemoSalesManager|crmsfa|
|DemoCSR|crmsfa|

b. TestRunner_09.java
package cucumber_TestCases_09;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions( features =
"src/main/java/feature/Bussiness_Scenarios_07.feature",
glue = "cucumber_TestCases_09",
tags= {"@Smoke, @Regression"}, monochrome=true
) //Any one of the Condition is meet and it will
execute
public class TestRunner_09 {

c. CucumberTestCase_09.java
package cucumber_TestCases_09;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.Scenario; //Added Cucumber API


import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_09 {

public static ChromeDriver driver;

Cucumber for Selenium Page 36


@Before
public void beforeScenario(Scenario sc) throws Exception{
System.out.println("Starting executig scenario " + sc.getName());

System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario(Scenario sc) {
System.out.println("Completing scenario " + sc.getName());

System.out.println("This will run after the Scenario");


driver.quit();
}

@And("Enter User Name_sc9 as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc9 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc9")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc9")


public void Verify() {
System.out.println("Login Successful");
}
}

Exercise -8
Multiple Grouping in single scenario in feature file with step definition: (Tags: common group to execute)

a. Bussiness_Scenarios_08.feature
Feature: Example Scenarios

# Scenario-10
@Smoke @Regression
Scenario: Login for leaftaps01

And Enter User Name_sc10 as DemoSalesManager


And Enter Password_sc10 as crmsfa

Cucumber for Selenium Page 37


When Click on Login button_sc10
Then Verify login is sucessful_sc10

@Sanity @Regression
Scenario Outline: Login for leaftaps02

And Enter User Name_sc10 as <uName> #added variable name and mention
examples multiple data
And Enter Password_sc10 as <password>
When Click on Login button_sc10
Then Verify login is sucessful_sc10
Examples:
|uName|password|
|DemoSalesManager|crmsfa|
|DemoCSR|crmsfa|

b. TestRunner_10.java
package cucumber_TestCases_10;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions( features =
"src/main/java/feature/Bussiness_Scenarios_08.feature",
glue = "cucumber_TestCases_10",
tags= {"@Smoke", "@Regression"},
monochrome=true
) //Both Conditions are meet and it will execute
public class TestRunner_10 {

c. CucumberTestCase_10.java
package cucumber_TestCases_10;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.Scenario; //Added Cucumber API


import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_10 {

public static ChromeDriver driver;

@Before
public void beforeScenario(Scenario sc) throws Exception{

Cucumber for Selenium Page 38


System.out.println("Starting executig scenario " + sc.getName());

System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario(Scenario sc) {
System.out.println("Completing scenario " + sc.getName());

System.out.println("This will run after the Scenario");


driver.quit();
}

@And("Enter User Name_sc10 as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc10 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc10")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc10")


public void Verify() {
System.out.println("Login Successful");
}
}

Exercise -9
Multiple Grouping in single scenario in feature file with step definition: (Tags : ~@S)
a. Bussiness_Scenarios_09.feature
Feature: Example Scenarios

# Scenario-10
@Smoke @Regression
Scenario: Login for leaftaps01

And Enter User Name_sc11 as DemoSalesManager


And Enter Password_sc11 as crmsfa
When Click on Login button_sc11
Then Verify login is sucessful_sc11

@Sanity @Regression

Cucumber for Selenium Page 39


Scenario Outline: Login for leaftaps02

And Enter User Name_sc11 as <uName> #added variable name and mention
examples multiple data
And Enter Password_sc11 as <password>
When Click on Login button_sc11
Then Verify login is sucessful_sc11
Examples:
|uName|password|
|DemoSalesManager|crmsfa|
|DemoCSR|crmsfa|

b. TestRunner_11.java
package cucumber_TestCases_11;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions( features =
"src/main/java/feature/Bussiness_Scenarios_08.feature",
glue = "cucumber_TestCases_10",
tags= {"~@S.*", "@Regression"}, monochrome=true
) // Start from 'S' groups and checks conditions
and it will execute
public class TestRunner_11 {

c. CucumberTestCase_11.java
package cucumber_TestCases_11;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.chrome.ChromeDriver;

import cucumber.api.Scenario; //Added Cucumber API


import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CucumberTestCase_11 {

public static ChromeDriver driver;

@Before
public void beforeScenario(Scenario sc) throws Exception{
System.out.println("Starting executig scenario " + sc.getName());

System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");

Cucumber for Selenium Page 40


driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps/control/main");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

@After
public void afterScenario(Scenario sc) {
System.out.println("Completing scenario " + sc.getName());

System.out.println("This will run after the Scenario");


driver.quit();
}

@And("Enter User Name_sc11 as (.*)")


public void UserName(String uName) {
driver.findElementById("username").sendKeys(uName);
}

@And("Enter Password_sc11 as (.*)")


public void Password(String password) {
driver.findElementById("password").sendKeys(password);
}

@When("Click on Login button_sc11")


public void LoginBtn() {
driver.findElementByClassName("decorativeSubmit").click();
}

@Then("Verify login is sucessful_sc11")


public void Verify() {
System.out.println("Login Successful");
}
}

Project: Page Object Model with Cucumber:


Below folder structure is the Page Object Model (POM) with Cucumber:

Cucumber for Selenium Page 41


Cucumber for Selenium Page 42

Вам также может понравиться