top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

CUCUMBER BDD Framework [Sample Code and Types to Consider in BDD]


PROJECT STRUCTURE




What is cucumber?

*Cucumber is a tool that supports Behavior Driven Development (BDD).

*It offers a way to write tests that anybody can understand, regardless

of their technical knowledge.

*In BDD, users first write scenarios or acceptance tests that describes

the behavior of the system from the customer's perspective, for review

and sign-off by the product owners before developers write their codes.

What language is used by Cucumber?

*Gherkin language is used by cucumber.

*Gherkin language uses several keywords to describe the behavior of

application such as Feature, Scenario, Scenario Outline, Given, When,

Then etc.

What is meant by a feature file?

*A Feature File is an entry point to the Cucumber tests.

*A feature file must provide a high-level description of an Application

Under Test.

*The first line of the feature file must start with the keyword ‘Feature’

*A feature file can contain a scenario or can contain many scenarios in a

single feature file but it usually contains a list of scenarios.

What is logging?

Logging is the process of writing log messages during the execution of a program to a central place.

If we use system.out.println , it shows only in console ,we will lose all logs when we close console.

Logger class : create object for logger class methods info, warn, error, fatal.

Log4j priority Levels

Debug< info< warn< error< fatal


Data Driven Testing:

  • DDT which allows to automatically run a test case multiple times with different input and validation values. As Selenium WebDriver is more an automated testing framework than a ready-to-use tool. It takes extra efforts to support data driven testing in automated tests.

  • This is very often required in any automated test to pass data or to use the same test again with different data set. And the good part is that the Cucumber inherently supports Data Driven Testing using Scenario Outline. There are different ways to use the data insertion within the Cucumber and outside the Cucumber with external files.

Data-Driven Testing in Cucumber

• Parameterization without Example Keyword

Data-Driven Testing in Cucumber using Scenario Outline

• Parameterization with Example Keyword

• Parameterization using Tables

Data-Driven Testing in Cucumber using External Files

• Parameterization using Excel Files

• Parameterization using Json

• Parameterization using XML

Scenario Outline - This is used to run the same scenario for 2 or more different sets of test data. E.g. In our scenario, if you want to register another user you can data drive the same scenario twice.

Examples - All scenario outlines have to be followed with the Examples section. This contains the data that has to be passed on to the scenario.


Sample Code

1.DATA DRIVEN USING DATATABLE

2.DATA DRIVEN USING EXAMPLES

3.DATA DRIVEN USING EXCEL WITH SHEET NAME AND ROW NUMBER

4.GETTING DATA FROM CONFIG.PRPOERTIES, CONSTANTS

5.GETTING HARDCODED VALUES WRITTEN IN FEATURE FILE

6.COMPARING ACTUAL OUTPUT WHEN EXECUTING CODE AND EXPECTED OUTPUT WRITTEN IN EXCEL

7.READING VALUE FROM CONFIG.PROPERTIES THROUGH CONFIG READER

8.GETTING DATA FROM EXCEL FILE STORED IN RESOURCE FOLDER

9.LOGGING DATA -CONNECTION BETWEEN LOG4J2.PROPERTIES AND JAVA CLASS FILE

10.SETTING CHROME BROWSER

11.PRINTING ALERT MESSAGE







1. DATA DRIVEN USING DATATABLE [io.cucumber.datatable.DataTable]

Here Data username is written in When Step in feature file

FEATURE FILE

1.Scenario: The user is presented with error message for empty fields below Password textbox
Given The user opens Register Page
When The user enters “username” with other fields empty and user clicks register button
| username |
| NumphysdetN |
Then It should display an error message “Please fill out this field.” below Password textbox


Here Data username and password is written in When Step in feature file



2.Scenario: The user is presented with error message for empty fields below confirm Password textbox
Given The user opens Register Page
When The user enters “username” and “password” with Password
Confirmation field empty and user clicks register button
| username          | password |
| NumphysdetN | sdetbatch |                  
Then It should display an error message “Please fill out this field.”below Password Confirmation textbox


Here Data username and password and confirm_password is written in When Step in feature file



3.Scenario: The user is presented with error message for password mismatch
Given The user opens Register Page
When The user enters “username” and different passwords in “password” and
“confirm_password” fields and user clicks register button
| username          | password       | confirm_password |
| NumphysdetN | sdetbatch       | password |
Then It should display an error message “password_mismatch”


PAGEOBJECT CLASS


Method to get data username from datable



public void enterUsername(DataTable dataTable) {
List<Map<String, String>> userdetail = dataTable.asMaps(String.class, String.class);
for (Map<String, String> mapData : userdetail) {
String userName = mapData.get(“username”);
Loggerload.info(“The user enter username as : “ +userName);
user_Name.sendKeys(userName);
}
}


Method to get data password from datable



public void enterPassword(DataTable dataTable) {
List<Map<String, String>> userdetail = dataTable.asMaps(String.class, String.class);
for (Map<String, String> mapData : userdetail) {
String pwd = mapData.get(“password”);
Loggerload.info(“The user enter password as : “ + pwd);
pass_word.sendKeys(pwd);
}
}


Method to get data confirm password from datable



public void enterConfmPassword(DataTable dataTable) {
List<Map<String, String>> userdetail = dataTable.asMaps(String.class, String.class);
for (Map<String, String> mapData : userdetail) {
String confirmpwd = mapData.get(“confirm_password”);
Loggerload.info(“The user enter confirm password as : “ +confirmpwd );
confirm_pwd.sendKeys(confirmpwd );
}
}

1.STEP DEFINITION
Here user enters only username field and submitting


@When(“The user enters {string} with other fields empty and user clicks register button”)
public void the_user_enters_with_other_fields_empty_and_user_clicks_register_button(String string, io.cucumber.datatable.DataTable dataTable) {
Loggerload.info(“The user enters username with other fields empty “ );
rp.enterUsername(dataTable);
rp.clickSubmitRegister();
String Page_Title=rp.getPageTitle();
Loggerload.info(“Page Title : “+Page_Title );

2.STEP DEFINITION
Here user enters only username field , password filed and submits

@When(“The user enters {string} and {string} with Password Confirmation field empty and user clicks register button”)
public void the_user_enters_and_with_password_confirmation_field_empty_and_user_clicks_register_button(String string, String string2, io.cucumber.datatable.DataTable dataTable) {
Loggerload.info(“The user enters username and password with Password Confirmation field empty “ );
rp.enterUsername(dataTable);
rp.enterPassword(dataTable);
rp.clickSubmitRegister();
}

3.STEP DEFINITION
Here user enters only username field , password filed and confirm password field and submits

@When(“The user enters a {string} with characters other than Letters, digits and @\\/.\\/+\\/-\\/_ with {string} and {string} and user clicks register button”)
public void the_user_enters_a_with_characters_other_than_letters_digits_and_with_and_and_user_clicks_register_button(String string, String string2, String string3, io.cucumber.datatable.DataTable dataTable) {
Loggerload.info(“The user enters a username with characters other than Letters, digits and @/./+/-/_ with password and confirm_password” );
rp.enterUsername(dataTable);
rp.enterPassword(dataTable);
rp.enterConfmPassword(dataTable);
rp.clickSubmitRegister();
}
2. DATA DRIVEN USING EXAMPLES :

Here data to be used is written in Examples Keyword in Scenario Outline

FEATURE FILE
To test with multiple sets of data, increasing test coverage by passing Data username, password and confirm_password

Scenario Outline: Getting register into page with username and password
Given The user opens Register Page
When The user clicks Register button after entering “<username>”, “<password>” and “<confirm_password>”
Then It should go to homepage and get message “New account created.You are logged in as Username”
Examples:
| username       | password        | confirm_password |
| username       | sdet                   | sdetbatch |
| Numphysdet  | sdetbatch       | sdetbatch |

PAGEOBJECT CLASS
Method to send username , passowrd and confirm_password

public void register_link(String username, String password, String confirm_password) throws InterruptedException {
user_Name.sendKeys(username);
pass_word.sendKeys(password);
confirm_pwd.sendKeys(confirm_password);
driver.findElement(registerSubmitButton).click();
}

STEP DEFINITION
Here user enters username , passowrd and confirm_password and submits

@When(“The user clicks Register button after entering {string}, {string} and {string}”)
public void the_user_clicks_register_button_after_entering_and(String username,String password,String confirm_password) throws InterruptedException {
rp.register_link(username, password, confirm_password);
Loggerload.info(“user successfully Registered”);
String Page_Title=rp.getPageTitle();
Loggerload.info(“Page Title : “+Page_Title );
}

3. DATA DRIVEN USING EXCEL WITH SHEET NAME AND ROW NUMBER:

Data driven can also be done using Excel sheet , using Sheet Number and Row Number , in this case , sheet number is Integer denoted as Index 0, written as <SheetNumber> without quotes

FEATURE FILE
Here data driven is done using sheet name and row number

ExcelReader
.txt
Download TXT • 6KB

Scenario Outline: user navigate to sign in page
Given user launches login page
When user login using username and password from given “<SheetName>” and <rownumber>
Examples:
|sheetName |rownumber|
|Sheet1            |0                      |
|Sheet1             |1                      |

PAGEOBJECT CLASS
Method to send username and password got from excel sheet and submit

public void loginWithCredentials(String username, String password) throws InterruptedException {
driver.findElement(login_Username).sendKeys(username);
driver.findElement(login_Password).sendKeys(password);
driver.findElement(login_Button).click();
}

STEP DEFINITION
Here data is taken from excel sheet , using excel reader

@When(“user login using username and password from given {string} and {int}”)
public void user_login_using_username_and_password_from_given_and(String sheetName, Integer rowNumber) throws IOException, InvalidFormatException, InterruptedException {
ExcelReader reader = new ExcelReader();
Loggerload.info(“User enter login credentials “);
List<Map<String, String>> testData=reader.getData(“C:/Users/Desktop/Numpy/Login.xlsx”,” Sheet1");
String User_name=testData.get(rowNumber).get(“username”); // Column heading
String Pass_word=testData.get(rowNumber).get(“password”); // Column heading
collection.loginWithCredentials(User_name, Pass_word);
Loggerload.info(“User redirected to login page “);
}

SheetName=Sheet1

username

password

expectedmessage

username1

sdetbatch

please check your password

sdetbatch

password1

please check your username

username1

password1

you are logged in


4. GETTING DATA FROM CONFIG.PRPOERTIES, CONSTANTS:
Here data is written in config.prpperties file , reading data from config.properties file using fileinputstream and properties class
FEATURE FILE
Here Key USERNAME and PASSWORD is mentioned in feature file

Scenario Outline: user navigate to datastructure page
Given user login with username “USERNAME” and password “PASSWORD” given through config
Given user launch datastructure page

CONFIG.PROPERTIES
Data is written as Key-Value pair

USERNAME=Numphysdet
PASSWORD=sdetbatch

CONSTANTS CLASS
Mentioning the data type of the value to be used

package constants;
public class Constants {
public static String user_name;
public static String pass_word;
}

PAGEOBJECT CLASS
Method to get value from config.properties file and assigning the data to constant variable and submiting the values assigned to the variable

private final static String propertyFilePath = “./src/test/resources/config.properties”;
private static Properties properties;
public void loginWithUernamePwd(String string, String string2) throws InterruptedException, IOException {
//ConfigReader.loadConfig();
FileInputStream stream = new FileInputStream(propertyFilePath);
properties = new Properties();
properties.load(stream);
//stream.close();
//properties.load(getClass().getResourceAsStream(“/config.properties”));
//PageFactory.initElements(driver, CollectionsPage.class);
Constants.user_name=properties.getProperty(“USERNAME”);
Constants.pass_word=properties.getProperty(“PASSWORD”);
driver.findElement(login_Username).sendKeys(Constants.user_name);
driver.findElement(login_Password).sendKeys(Constants.pass_word);
driver.findElement(login_Button).click();
}

STEP DEFINITION
Here user enters value got from config file and submitting

@Given(“user login with username {string} and password {string} given through config”)
public void user_login_with_username_and_password_given_through_config(String string, String string2) throws InterruptedException, IOException {
collection.loginWithUernamePwd(string, string2);
}

5. GETTING HARDCODED VALUES WRITTEN IN FEATURE FILE
Entering Hardcoded values in feature file
FEATURE FILE

Scenario Outline: user navigate to array page and works on Arrays in Python
Given user login with username “Numphysdet” and password “sdetbatch”
Given user clicks “Get started” in Array field

PAGEOBJECT CLASS
Method for passing the hardcoded values mentioned in feature file and submitting

public void loginWithCredentials(String username, String password) throws InterruptedException {
driver.findElement(login_Username).sendKeys(username);
driver.findElement(login_Password).sendKeys(password);
driver.findElement(login_Button).click();
}

STEP DEFINITION
Here user enters username and password and login

@Given(“user login with username {string} and password {string}”)
public void user_login_with_username_and_password(String username, String password) throws IOException, InterruptedException {
collection.LoginPage();
collection.loginWithCredentials(username, password);
}

6. COMPARING ACTUAL OUTPUT WHEN EXECUTING CODE AND EXPECTED OUTPUT WRITTEN IN EXCEL
ELEMEMNT UTILS CLASS
Here Wait statement is given , to wait for each element for the visibility of that element in DOM

String Excelpath = ConfigReader.getexcelfilepath();

public void WaitForElement(WebElement element) {
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOf(element));
}


Reading result column data from excel


public String getResultfromExcel(String sheetName, int rownumber) throws InvalidFormatException, IOException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testdata = reader.getData(Excelpath, sheetName);
result = testdata.get(rownumber).get(“Result”);
Loggerload.info(“Expected result from Excel sheetname “ + sheetName + “ and “ + rownumber + “ : “ + result);
return result;
}

CONFIG.PROPERTIES

excelfilepathCode=./src/test/resources/Exceldata/Login.xlsx

CONFIG READER
Getting excel file path location from config.properties file

public static String getexcelfilepath() {
String excelfilelpath = properties.getProperty(“excelfilepathCode”);
if (excelfilelpath != null)
return excelfilelpath;
else
throw new RuntimeException(“Excel file path not specified in the Configuration.properties file.”);
}

PAGEOBJECT CLASS

static ElementsUtils elementUtil = new ElementsUtils();
String Excelpath = ConfigReader.getexcelfilepath();
static WebElement output;


Getting expected result from excel


public static String getExpectedResult(String sheetName, Integer rowNumber) throws InvalidFormatException, IOException {
String expectedResult = elementUtil.getResultfromExcel(sheetName, rowNumber);
return expectedResult;
}

Getting Actual output when the code runs

public static String getActualResult() {
elementUtil.WaitForElement(output);
return output.getText();
}

STEP DEFINITION
Comparing actual output and expected output and asserting with the message

@Then(“user enters code in tryEditor from {string} and {int} then click run , output is printed”)
public void user_enters_code_in_try_editor_from_sheet_number_and_then_click_run_output_is_printed(String sheetName, Integer rowNumber) throws InvalidFormatException, IOException {
collection.enterPythonCode(sheetName, rowNumber);
expectedMesg=collection.getExpectedResult(sheetName, rowNumber);
String actualSuccMessg = CollectionsPage.getActualResult();
Loggerload.info(“Actual result: “+actualSuccMessg );
assertEquals(actualSuccMessg, expectedMesg,” Results do not match”);
}

7. READING VALUE FROM CONFIG.PROPERTIES THROUGH CONFIG READER

Key-Value pair is written in config.properties file , the vlaue written in properties file is read by config reader

PAGEOBJECT CLASS
Launching login page url got from config reader

private final static String propertyFilePath = “./src/test/resources/config.properties”;
private static Properties properties;
public void LoginPage() throws IOException {
ConfigReader.loadConfig();
String URL=ConfigReader.getLoginPage();
driver.get(URL);
}

CONFIG.PROPERTIES
Key-Value pair

loginpage=https://*************************.com

CONFIG.READER
File input stream to get config.properties saved in resource folder

public class ConfigReader {
private static Properties properties;
private final static String propertyFilePath = “./src/test/resources/config.properties”;
public static void loadConfig() throws IOException {
try
{FileInputStream stream = new FileInputStream(propertyFilePath);
properties = new Properties();
try {
properties.load(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(“Configuration.properties not found at “ + propertyFilePath);
}
}

From properties file getting the loginpage url


public static String getLoginPage() {
String loginurl = properties.getProperty(“loginpage”);
if (loginurl != null)
return loginurl;
else
throw new RuntimeException(“Homeurl not specified in the Configuration.properties file.”);
}

8. GETTING DATA FROM EXCEL FILE STORED IN RESOURCE FOLDER
CONFIG.PROPERTIES
Here excel file used for data driven is stored in resource folder , and the path of the file is taken and given in properties file as key-value pair

excelfilepathCode=./src/test/resources/Exceldata/Login.xlsx

ELEMENT UTILS
Using Excel reader to read data from excel ,Excel file path given in config properties file is read using properties in config reader and assgined to Excelpath

String Excelpath = ConfigReader.getexcelfilepath();

public String getCodefromExcel(String sheetName, int rownumber) throws InvalidFormatException, IOException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testdata = reader.getData(Excelpath,”pythonCode”);
code = testdata.get(rownumber).get(“python_Code”); //COLUMN HEADING
result = testdata.get(rownumber).get(“Result”); //COLUMN HEADING
return code;
}

Sheet Name =pythonCode

python_Code

Result

print("hellow")

hellow

print("hellow world")

hellow world

9. LOGGING DATA - CONNECTION BETWEEN LOG4J2.PROPERTIES AND JAVA CLASS FILE

log4j2.properties has configuration for logging the output and apache logManager and logger is used for logging operations , like logging the output for info, error, warn , debug
LOGGER LOAD JAVA FILE
for logging the info, similarly method can be written for error, warn and debug

Log4j2
.txt
Download TXT • 674B

LoggerLoad
.txt
Download TXT • 626B

public class Loggerload {
private static Logger logger = (Logger) LogManager.getLogger();
public static void info(String message) {
logger.info(message); 
}

STEP DEFINITION
Here we have used logger info to log the title of the page

@Then(“user should be redirected to the homepage and see {int} different collections”)
public void user_should_be_redirected_to_the_homepage_and_see_different_collections(Integer int1) {
String Page_Title= collection.getPageTitle();
Loggerload.info(“Page Title : “+Page_Title );
assertEquals(Page_Title, “NumpyNinja”, “Title do not match”);
}

10. SETTING CHROME BROWSER
Setting up chrome browser to be used for executing the code
CONFIG.PROPERTIES
Assigning chrome to the browser type

browser=chrome

CONFIG.READER
Checking if the browser type is mentioned , if mentioned, return the type of browser going to be used for code execution

public static String getBrowserType() {
String browser = properties.getProperty(“browser”);
Loggerload.info(“Get property BrowserType”);
if (browser != null)
return browser;
else
throw new RuntimeException(“browser not specified in the Configuration.properties file.”);
}
}

DRIVER FACTORY
Cross Browser Testing can be done by using if-else or switch case , to select type of browser to be used [firefox, edge, chrome...]

if(browser.equalsIgnoreCase(“chrome”))
{
Loggerload.info(“Testing on chrome”);
//System.setProperty(“webdriver.chrome.driver”, driverLocation);
WebDriverManager.chromedriver().setup();
//WebDriverManager.chromedriver().clearDriverCache();
//WebDriverManager.chromedriver().clearResolutionCache();
//WebDriverManager.chromedriver().browserVersion(“110.0.0”).setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setScriptTimeout(Duration.ofSeconds(30));
chromeOptions.setPageLoadTimeout(Duration.ofMillis(30000));
chromeOptions.setImplicitWaitTimeout(Duration.ofSeconds(20));
chromeOptions.addArguments("--remote-allow-origins=*");	 
driver =new ChromeDriver(chromeOptions);
//System.setProperty(“webdriver.chrome.driver”, driverLocation);
}

11. PRINTING ALERT MESSAGE
If an alert pops ups , we can read the alert and print the alert message and then we can click accept the alert

public static String getErrorText() throws InterruptedException {
Thread.sleep(1000);
String errorMsg = driver.switchTo().alert().getText();
Loggerload.info(“The Error Message is:” +errorMsg);
driver.switchTo().alert().accept();
return errorMsg;
}

You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.


Happy Learning

849 views3 comments
bottom of page