Cucumber with Java Tutorial and Framework.
Cucumber Framework Demo Video:
Below is a complete Cucumber tutorial and base framework kept on Git Hub at below location:
https://github.com/akashdktyagi/AutomationPoCCucumber
This framework is created for the new students of cucumber and provides a base cucumber eco-system skeleton upon which you can build your own requirements. It has few test cases already automated.
I plan to enhance it further to make it a full fledged automation Framework. Framework would have below features:
- Maven for build and Configurations
- Junit as runner
- Cucumber
- Selenium
- Page object Model/Page Factory
- Cucumber Reports for high level logs
- Extent Reports for high level logs
- Log4J for Logging and low level logs
Description: For full and updated code visit GitHub repo path mentioned at the top of this post.
Below is the sample code.
- How to Install it. Plugin and Dependencies
- Eclipse Market Place, search for Cucumber
- Or if there is an error in above step; try with Help->Install->new Software and follow the steps here: https://github.com/cucumber/cucumber-eclipse-update-site-snapshot
- Above steps is for Installing Cucumber Plugin in eclipse, it has nothing do with the execution of cucumber, it is just to feciliate easy development of cucumber FW in eclipse.
- To actually use cucumber you need below dependencies in your maven pom file.
-
123456789101112131415161718192021222324252627282930<dependencies><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>3.141.59</version></dependency><dependency><groupId>io.cucumber</groupId><artifactId>cucumber-java</artifactId><version>${cucumber.version}</version><scope>test</scope></dependency><dependency><groupId>io.cucumber</groupId><artifactId>cucumber-junit</artifactId><version>${cucumber.version}</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>
- Test Runner.java: To Execute the Cucumber use below class.For full and updated code visit GitHub repo path mentioned at the top of this post.
-
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556package bddcucumber.runner;import org.junit.runner.RunWith;import cucumber.api.CucumberOptions;import cucumber.api.junit.Cucumber;/** Cucumber Options:* 1. Plugin : For reporting and output folders configs* a. pretty* b. HTML* c. JSON* 2. DryRun: For getting the step Defs info for un-implemented steps* 3. Strict: if true then , exec fails if step def is not found for a step* 4. Monochrome:default is false. Console is more readable if set as true* 5. Features: mention the feature file location, cucumber can find all the .feature files* in all the package and subpackages* 6. Glue: To mention step defs location of the Feature files.* 7. Snippet : To generate Snippets in specific format of underscore or camel case* 8. Tags: for grouping of the tests* Not: tag{"~@reg"}* And: tag{"@reg","@smoke"}* or: tag{"@reg,@smoke"}* and or not together : tag{"@reg,@smoke","~sanity"}** For Extent Report pacakge name has been added under Plugin section* For Details on How to Add Extent Report Cucumber Adapter* follow below links:* http://extentreports.com/docs/versions/4/java/cucumber4.html* http://extentreports.com/docs/versions/4/java/extentservice.html* https://github.com/extent-framework/extentreports-cucumber4-adapter** To Run from Command Line: mvn test –DCucumber.options=”Your Options”* https://www.toolsqa.com/selenium-cucumber-framework/run-cucumber-test-from-command-line-terminal/*/@RunWith(Cucumber.class)@CucumberOptions(features = {"classpath:features/healthcare"},//,"classpath:features/zeroapp"},glue= {"bddcucumber/healthcare/stepdefs"},//"bddcucumber/zeroapp/stepdefs"},//tags = {"@register_a_patient"},//,"@zero_app"},//login_feature, register_a_patientplugin ={"pretty" , "html:target/CucumberResults","com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"},//"json:target/cucumber-report.json"monochrome = true,dryRun=false)public class TestRunner {//This class will be empty/** Important Links;* junit-cucumber Options* https://testingneeds.wordpress.com/2015/09/15/junit-runner-with-cucumberoptions/* If ur getting error with Cucumber and Extent report Adapter* https://stackoverflow.com/questions/54721039/getting-initialization-error-noclassdeffounderror-cucumber-runtime-io-urloutpu*/}
- Feature Files: For full and updated code visit GitHub repo path mentioned at the top of this post.
-
123456789101112131415161718192021222324252627282930@OpenMRS @reg @login_featureFeature: LoginTo vaidate and check all aspects of Login functionaity#Background:@login @positiveScenario: Succesfull Login validationGiven As a user when I launch application in "chrome"And navigate to url as "https://demo.openmrs.org/openmrs/index.htm"When I enter user name as "admin"And I enter password as "Admin123"And I click submit buttonThen I should be logged in to the application with title as "Home"And close the browser@login @negativeScenario Outline: User should not be able to login with in valid credentialsGiven As a user when I launch application in "chrome"And navigate to url as "https://demo.openmrs.org/openmrs/index.htm"When I enter user name as "<Username>"And I enter password as "<Password>"And I click submit buttonThen application should give error message as "<ErrorMsg>"And close the browserExamples:| Username | Password | ErrorMsg || admin | wrng | Invalid username/password. Please try again. || wrng | Admin123 | Invalid username/password. Please try again. |
123456789101112131415161718192021222324252627282930313233343536373839#Author: your.email@your.domain.com#Keywords Summary :#Feature: List of scenarios.#Scenario: Business rule through list of steps with arguments.#Given: Some precondition step#When: Some key actions#Then: To observe outcomes or validation#And,But: To enumerate more Given,When,Then steps#Scenario Outline: List of steps for data-driven as an Examples and <placeholder>#Examples: Container for s table#Background: List of steps run before each of the scenarios#""" (Doc Strings)#| (Data Tables)#@ (Tags/Labels):To group Scenarios#<> (placeholder)#""## (Comments)#Sample Feature Definition Template@OpenMRS @register_a_patientFeature: validate register patientTo check when user register a patient after entering all the details of the patient then,patient records are saved in to the system and is displayed in Patient Records tabBackground:Given As a user when I launch application in "chrome"And navigate to url as "https://demo.openmrs.org/openmrs/index.htm"When I enter user name as "admin"And I enter password as "Admin123"And I click submit buttonThen I should be logged in to the application with title as "Home"And I click on "RegisterAPatient" tab@register_a_patient @positiveScenario: Register a PatientGiven Register a Patient Form is displayedWhen register a patient form fields is filled as "Akash","Tyagi","Male","12/12/84","Add1","Add2","Pune","MH","India","411012","1234567891"And confirm button is clickedThen patient is register in the system with patient Id generatedAnd patient records are displayed in Find patient tab under menu
-
- Step Definitions Login: For full and updated code visit GitHub repo path mentioned at the top of this post.
-
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114package bddcucumber.healthcare.stepdefs;import java.util.concurrent.TimeUnit;import org.junit.Assert;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.PageFactory;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;import bddcucumber.healthcare.po.PO_Login;import bddcucumber.managers.WebDriverManagerSingleton;import cucumber.api.Scenario;import cucumber.api.java.After;import cucumber.api.java.Before;import cucumber.api.java.en.Given;import cucumber.api.java.en.Then;import cucumber.api.java.en.When;public class STEPS_Login {WebDriver driver;WebDriverManagerSingleton browserManager;Scenario scn ;PO_Login PO_Login;@Beforepublic void SetUp(Scenario s) {this.scn = s;}@Given("navigate to url as {string}")public void navigate_to_url(String url) {driver.get(url);//InitializePO_Login = PageFactory.initElements(driver, PO_Login.class);}@Given("As a user when I launch application in {string}")public void as_a_user_launch_application(String browser) {if (browser.equalsIgnoreCase("chrome")) {//System.setProperty("webdriver.chrome.driver", "E:\\_AkashStuff\\Automation\\dependencies\\chromedriver\\chromedriver.exe");//driver = new ChromeDriver();browserManager= WebDriverManagerSingleton.getInstanceOfWebDriverManager();driver = browserManager.getDriver();}else if (browser.equalsIgnoreCase("firefox")) {System.setProperty("webdriver.gecko.driver", "E:\\_AkashStuff\\Automation\\dependencies\\gecko\\geckodriver.exe");//driver = new FirefoxDriver();}}@When("I enter user name as {string}")public void enter_user_name(String u) {PO_Login.SetUserName(u);scn.write("Entered Username: " + u);}@When("I enter password as {string}")public void enter_password(String p) {PO_Login.SetPassword(p);scn.write("Entered password: " + p);}@When("I click submit button")public void click_submit_button() {PO_Login.ClickSubmitButton();scn.write("Click Submit Button");}@Then("I should be logged in to the application with title as {string}")public void should_be_logged_in_to_the_application(String title) {//Wait for 20 seconds for title to AppearWebDriverWait wait = new WebDriverWait(driver, 20);wait.until(ExpectedConditions.titleIs(title));String expected_title = title;String actual_title = driver.getTitle();Assert.assertEquals(expected_title, actual_title);scn.write("Title Matched. Login Successfull");}//@After@Then("close the browser")public void close_the_browser() {// Write code here that turns the phrase above into concrete actionsbrowserManager.CloseDriver();scn.write("Browser Closed");}@Then("application should give error message as {string}")public void application_should_give_error_message_as(String string) {String actual = PO_Login.GetErrorMessage();String expected = string.trim();if (actual.contains(expected)) {Assert.assertTrue("Actual and Expected Error Message Matched", true);scn.write("PASSED: Actual and Expected Error Message Matched");}else {Assert.assertTrue("Actual and Expected Error Message did not Matched", false);scn.write("FAILED: Actual and Expected Error Message did not Matched ");}}}
2. Step Definition Register a new patient:For full and updated code visit GitHub repo path mentioned at the top of this post.-
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package bddcucumber.healthcare.stepdefs;import java.util.concurrent.TimeUnit;import org.junit.Assert;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.PageFactory;import bddcucumber.healthcare.po.PO_Home;import bddcucumber.healthcare.po.PO_Login;import bddcucumber.healthcare.po.PO_RegisterAPatient;import bddcucumber.healthcare.po.PO_Cmn;import bddcucumber.managers.WebDriverManagerSingleton;import cucumber.api.Scenario;import cucumber.api.java.Before;import cucumber.api.java.en.Given;import cucumber.api.java.en.Then;import cucumber.api.java.en.When;public class STEPS_RegisterAPatient {WebDriverManagerSingleton browserManager = WebDriverManagerSingleton.getInstanceOfWebDriverManager();WebDriver driver =browserManager.getDriver() ;PO_Home PO_Home= PageFactory.initElements(driver, PO_Home.class);PO_Cmn PO_Cmn= PageFactory.initElements(driver, PO_Cmn.class);PO_RegisterAPatient PO_RegisterAPatient= PageFactory.initElements(driver, PO_RegisterAPatient.class);Scenario scn ;@Beforepublic void SetUp(Scenario s) {this.scn = s;}@Then("I click on {string} tab")public void i_click_on_tab(String string) {PO_Home.Click_Link_register();}@Given("Register a Patient Form is displayed")public void register_a_Patient_Form_is_displayed() {String actual = PO_Cmn.GetBreadCrumbText();String expected = "Register a patient";if (actual.contains(expected)) {scn.write("Register a patient page is displayed");Assert.assertTrue("Register a patient page is displayed", true);}else {scn.write("Register a patient page is not displayed");Assert.assertTrue("Register a patient page is displayed", false);}}@When("register a patient form fields is filled as {string},{string},{string},{string},{string},{string},{string},{string},{string},{string},{string}")public void all_the_register_a_patient_form_fields_is_filled_as(String name, String familyname, String gender, String string4, String string5, String string6, String string7, String string8, String string9, String string10, String string11) {PO_RegisterAPatient.SetName(name);PO_RegisterAPatient.SetFamilyName(familyname);PO_RegisterAPatient.ClickGenderSideMenu();PO_RegisterAPatient.SelectGender(gender);}@When("confirm button is clicked")public void confirm_button_is_clicked() {// Write code here that turns the phrase above into concrete actionsthrow new cucumber.api.PendingException();}@Then("patient is register in the system with patient Id generated")public void patient_is_register_in_the_system_with_patient_Id_generated() {// Write code here that turns the phrase above into concrete actionsthrow new cucumber.api.PendingException();}@Then("patient records are displayed in Find patient tab under menu")public void patient_records_are_displayed_in_Find_patient_tab_under_menu() {// Write code here that turns the phrase above into concrete actionsthrow new cucumber.api.PendingException();}}
-
-
- Page object model for login page: For full and updated code visit GitHub repo path mentioned at the top of this post.
-
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package bddcucumber.healthcare.po;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.support.FindBy;import org.openqa.selenium.support.How;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;public class PO_Login {//Step 1 DriverWebDriver driver;//Step: Paramatrized constructorpublic PO_Login(WebDriver d) {driver = d;}//Elements or Locators@FindBy(how = How.ID,using = "username")WebElement txtbx_username;@FindBy(how = How.ID,using = "password")WebElement txtbx_password;@FindBy(how = How.ID,using = "loginButton")WebElement btn_submit;@FindBy(how = How.ID,using = "Outpatient Clinic")WebElement tab_outpatient_clinic;@FindBy(how = How.ID,using = "error-message")WebElement txt_error_msg;//Methodspublic void SetUserName(String u) {txtbx_username.sendKeys(u);}public void SetPassword(String u) {txtbx_password.sendKeys(u);}public void ClickSubmitButton() {tab_outpatient_clinic.click();btn_submit.click();}public String GetErrorMessage() {WebDriverWait wait = new WebDriverWait(driver, 20);wait.until(ExpectedConditions.visibilityOf(txt_error_msg));return txt_error_msg.getText();}}
-
- Web Driver Manager: Driver has to be shared across different step definition class files. There can be multiple approaches. This framework uses concept of Singleton class for providing unique instance of Web Driver. Check below code:
-
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556package bddcucumber.managers;import java.util.concurrent.TimeUnit;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;/** Author: Akash* Date: 15Jun2019* Usage Example:* WebDriverManagerSingleton browserManager= WebDriverManagerSingleton.getInstanceOfWebDriverManager();* driver = browserManager.getDriver();*/public class WebDriverManagerSingleton {//Instance of Singleton Classprivate static WebDriverManagerSingleton instanceOfSingletonClass=null;private static WebDriver driver;//Private Constructorprivate WebDriverManagerSingleton() {System.setProperty("webdriver.chrome.driver", "E:\\_AkashStuff\\Automation\\dependencies\\chromedriver\\chromedriver.exe");driver = new ChromeDriver();driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);}//To create instance of Classpublic static WebDriverManagerSingleton getInstanceOfWebDriverManager() {if(instanceOfSingletonClass==null) {instanceOfSingletonClass = new WebDriverManagerSingleton();}return instanceOfSingletonClass;}//to get Driverpublic WebDriver getDriver() {if (driver==null) {System.setProperty("webdriver.chrome.driver", "E:\\_AkashStuff\\Automation\\dependencies\\chromedriver\\chromedriver.exe");driver = new ChromeDriver();driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);}return driver;}public void CloseDriver() {if (!(driver==null)) {driver.quit();driver = null;}}}
-
For full and latest code, check git hub link: