Tuesday, 22 May 2018

CUCUMBER FRAMEWORK


CUCUMBER FRAMEWORK

Create Maven project
Group id:com
Aritifact Id:Cucumber





















For Cucumber plug in




Dependencies for the framework [POM.XML]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com</groupId>
  <artifactId>Cucumber1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Cucumber1</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm</artifactId>
<version>1.2.5</version>
<type>pom</type>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm-deps</artifactId>
<version>1.0.5</version>
</dependency>

<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>1.0.0</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>



<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.5.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.relevantcodes/extentreports -->
<dependency>
    <groupId>com.relevantcodes</groupId>
    <artifactId>extentreports</artifactId>
    <version>2.41.0</version>
</dependency>

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>2.9.0</version>
    <scope>test</scope>
</dependency>


<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.jayway.restassured/json-schema-validator -->
<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.2.0</version>
</dependency>
    
  </dependencies>
</project>



To display Navigator
Window->Show View-> Navigator


Create the below folder structure




For the above folders just right click on desired folder and add the respective folder


For Resources folder

Right click on the project->properties->Sources->Cucumber/src/test/java->Add folder->test->Create New folder->folder name- resources





















Add folder





















New Folder


















Create feature folder and feature file (Facebooklogin.feature)















FacebookLogin.feature





Create runner package and FacebookloginFeatureRunner.java




















FacebookloginFeature Runner [class file]










Create TestNg folder and TestNg.xml

























TestNg.xml





Right click on TestNg.xml and run



Below output is displayed in Console







Create stepDefinitons folder under framework and create LoginToFacebook class




























Copy the console output[ methods-Given,When, Then] to LoginToFacebook class























LoginToFacebook-Step Definition

package framework.stepDefinition;


import com.relevantcodes.extentreports.LogStatus;

import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import framework.TestBase.TestBase;
import framework.configReader.ObjectRepo;
import framework.pageObject.Login;

public class LoginToApplication {

Login l= new Login(TestBase.driver);
@Given("^Enter the url and launch the application$")
public void enter_the_url_and_launch_the_application() throws Throwable {
TestBase.driver.get(ObjectRepo.reader.getWebsite());
TestBase.logger.info("Enter the URL and launch application --> "+ ObjectRepo.reader.getWebsite());
TestBase.extentlogger = TestBase.extent.startTest("Enter the URL and launch application -->passTest");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}

@And("^I enter username$")
public void i_enter_username() throws Throwable {
try{
TestBase.logger.info("Enter username --> ");

l.enterUsername("sagarseleniumstl@gmail.com");
  // System.out.println("enter username");
  // TestBase.type("Login_username", "Username");
   TestBase.extentlogger = TestBase.extent.startTest("Enter username ");
   TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");

}
}

@And("^I enter password$")
public void i_enter_password() throws Throwable {
try{
TestBase.logger.info("Enter password");
l.enterPassword("sagarsomaiah");
  //System.out.println("enter password");
// TestBase.type("Login_password", "Password");
  TestBase.extentlogger = TestBase.extent.startTest("Enter password");
  TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");

}
}

@And("^I click on login button$")
public void i_click_on_login_button() throws Throwable {
try{

TestBase.extentlogger = TestBase.extent.startTest("click login button-->");

l.clickSubmit();
TestBase.logger.info("Click submit");
//System.out.println("click login");
//TestBase.click("Login_submit");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");
}
}

@Then("^User is succesfully logged$")
public void user_is_succesfully_logged() throws Throwable {
try{
TestBase.extentlogger = TestBase.extent.startTest("logged successfully-->");
TestBase.logger.info("Logged successfully");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
   //System.out.println("logged");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");
}
}
}




Create below folders in src/main




























Note: Create Resource folder is the same way mentioned earlier( Right click project->Buildpath->source-src/main-new folder)


Package Explorer view






















Log4j.properties

# Define the root logger with appender file
log4j.rootLogger = INFO, FILE,stdout,HTML

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=selenium.out
log4j.appender.FILE.Append=false
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9


log4j.appender.HTML=org.apache.log4j.FileAppender
log4j.appender.HTML.File=application.html
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application log
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Append=false


# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n






Config.properties





Create configreader under framework and PropertyFileReader.java

















Create two classes-> DateTimeHelper.java & ResourceHelper.java under utility folder




















ResourceHelper.java

package com.cucumber.framework.utility;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ResourceHelper {
public static String getResourcePath(String resource) {
String path = getBaseResourcePath() + resource;
return path;
}
public static String getBaseResourcePath() {
String path = System.getProperty("user.dir");
System.out.println(path);
return path;
            }
public static InputStream getResourcePathInputStream(String path) throws FileNotFoundException{
return new FileInputStream(ResourceHelper.getResourcePath(path));
            }
public static void main(String[] args) throws FileNotFoundException {
//System.out.println(ResourceHelper.getResourcePath("configfile/"+ "config.properties"));   
getBaseResourcePath() ;
            }}



PropertyFileReader.java

package com.cucumber.framework.configreader;
public class PropertyFileReader implements ConfigReader{
            private Properties prop = null;
            public PropertyFileReader() {
            prop = new Properties();
            try {
            prop.load(ResourceHelper.getResourcePathInputStream("/src/main/resources/configfile/config.properties"));
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }}
            public String getUserName() {
                        return prop.getProperty("Username");
            }
            public String getPassword() {
                        return prop.getProperty("Password");
            }
            public String getWebsite() {
                        return prop.getProperty("Website");
            }
            public int getPageLoadTimeOut() {
                        return Integer.parseInt(prop.getProperty("PageLoadTimeOut"));
            }
            public int getImplicitWait() {
                        return Integer.parseInt(prop.getProperty("ImplcitWait"));
            }
            public int getExplicitWait() {
                        return Integer.parseInt(prop.getProperty("ExplicitWait"));
            }
            public String getDbType() {
                        return prop.getProperty("DataBase.Type");
            }
            public String getDbConnStr() {
                        return prop.getProperty("DtaBase.ConnectionStr");
            }
            public BrowserType getBrowser() {
                        return BrowserType.valueOf(prop.getProperty("Browser"));
            }




TestBase.java

package framework.TestBase;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

import com.relevantcodes.extentreports.ExtentReports;

import cucumber.api.java.After;
import cucumber.api.java.Before;
import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
import framework.Configuration.Browser.BrowserType;
import framework.Configuration.Browser.ChromeBrowser;
import framework.Configuration.Browser.FirefoxBrowser;
import framework.Utility.Screenshots;
import framework.configReader.ObjectRepo;
import framework.configReader.PropertyFileReader;

public class TestBase {

public static WebDriver driver;
public static final Logger logger=Logger.getLogger(TestBase.class.getName());
public static ExtentReports extent;
public static com.relevantcodes.extentreports.ExtentTest extentlogger;

public WebDriver getBrowserObject(BrowserType bType) throws Exception {

try {

switch (bType) {

case Chrome:
ChromeBrowser chrome = ChromeBrowser.class.newInstance();
return chrome.getChromeDriver();

case Firefox:
FirefoxBrowser firefox = FirefoxBrowser.class.newInstance();
return firefox.getFirefoxDriver();

default:
throw new Exception(" Driver Not Found : " + new PropertyFileReader().getBrowser());
}
} catch (Exception e) {

throw e;
}
}

public void setUpDriver(BrowserType bType) throws Exception {

driver = getBrowserObject(bType);

driver.manage().window().maximize();

}

@Before()
public void before() throws Exception {
ObjectRepo.reader = new PropertyFileReader();
setUpDriver(ObjectRepo.reader.getBrowser());
String log4jpath=System.getProperty("user.dir")+"\\log4j.properties";
//System.out.println(log4jpath);

PropertyConfigurator.configure(log4jpath);

//*********************************************

}

 @After()
public void after(){

extent.flush();
       driver.quit();
}


public  TestBase(){

extent = new ExtentReports (System.getProperty("user.dir") +"/test-output/ExtentReport.html", true);

extent
                .addSystemInfo("Host Name", "SAGAR PC")
                .addSystemInfo("Environment", "Cucumber BDD Framework")
                .addSystemInfo("User Name", "Sagar Somaiah");
                extent.loadConfig(new File(System.getProperty("user.dir")+"\\src\\main\\resources\\ConfigFile\\extent-config.xml"));
}
 }



Loginpage

package framework.pageObject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class Login {

WebDriver driver;

@FindBy(xpath="//input[@id='email']")
WebElement username;

@FindBy(xpath="//input[@id='pass']")
WebElement password;

@FindBy(xpath="//input[@value='Log In']")
WebElement submit;

public Login(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);

}

public void enterUsername(String username){
//log.info("clicked on sign in link...");
this.username.sendKeys(username);
}



public void enterPassword(String password){
//log.info("entering password...."+password);
this.password.sendKeys(password);
}
public void clickSubmit(){
this.submit.click();
}
}






Tuesday, 20 November 2012

To generate screen shot

To capture screenshot just place the below code in your script sometimes you might be running your script and you wanted to look what went wrong in application so you can capture the screen shot so you get a clear idea what went wrong on other side of your application.

In the below program I made it a function so that use place it in reusable section and pass paramaters such as file name and driver. It creates a folder by name screenshots and saves the screen shots as file name specified and prints you the location.


Reusable function



public static Object screenshot(String filename,WebDriver driver)
     {

try {

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir")+"//screenshots//"+filename+".jpg"));
System.out.println("Output screenshot stored at "+Calendar.getInstance().getTime()+ " in the path-->  "+System.getProperty("user.dir")+"\\screenshots\\");
String path="Output screenshot stored at "+Calendar.getInstance().getTime()+ " in the path-->  "+System.getProperty("user.dir")+"\\screenshots\\";

return path;

}
catch (IOException e)
{

e.printStackTrace();
System.out.println(filename+"Screenshot Failed to capture screenshot refer above details");

}
  return null;
}



The below is non reusable code to capture screenshot.



public static Object screenshot()
{

try {

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C://"+"//screenshots//"+filename+".jpg"));
}
 catch (IOException e)
{

e.printStackTrace();

}



Generate Random Number

There might be a need we could like to generate some random number to pass as test data to application, I wondered i could write a function so that each time it generates some random number so that i can run these scripts multiple times without worrying about the test data and guess what we can even pass the range whether you need single digit or two or digit or etc.



The below program illustrates random number generation within limit specified(10000).





 public static String getID(){

  int n=351;
 double d=0;          
 String Random;          
   int num=1;  
   {                    
while(true)          
{   
    
int final_limit=10000; //Specifiy the maximum limit          
d=Math.random()*final_limit;          
 num=(int)d;          
Random=String.valueOf(num);          
break;          
         
}
         
return Random;  

//This will return random number every time you run within 10000(specified limit)     
}   
    
}          


       

How to read values from Excel in Selenium Webdriver

One of the most aspect and beneficial of any automation tool is how well it can support parameterization. When one means parametization it is how effectively it can read and write values from excel. The below program illustrates an example to read values from excel, before executing the program we need to add jxl jars to java build path.


Download jars from here    jxl jars


package exchange.skills.com;

import java.io.File;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class Data_driven {
public String[][] getXLData(String location, String sheetname)
    {
            Workbook w = null;
            try {
                    w = Workbook.getWorkbook(new File(location));
            } catch (BiffException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            }
            Sheet s = w.getSheet(sheetname);
            String a[][] = new String[10][10];
            try
            {
            for (int j=0;j<s.getColumns();j++)
            {
                    for (int i=0;i<s.getRows();i++)
                    {
                            a[j][i] = s.getCell(j, i).getContents();
                            System.out.println(j+" and "+i+" "+a[j][i]);//Prints cell content one by one
                    }
            }


            }
            catch(Exception e)
            {
                    e.printStackTrace();
            }
            return a;
 
}
public static void main(String[] args) {
Data_driven n= new Data_driven();
//n.getXLData("location of excel file stored","sheet name")
n.getXLData("C:\\tc.xls", "sheet");//File where excel is placed-specify 2007 or save as excel workbook
}
}

Handling Dynamic Object using Action Builder class

The below script illustrates the use of action builder class to work on hidden object.


There is no direct approach to work on hidden objects using selenium webdriver, when i mean hidden objects sometimes we drag our mouse over something and we get to see some list which is clickable, these list are not popped up if we click on those links only dragging a mouse over that link will actually display the contents. To work with such kind we need to action builder class.
What Action builder class does? It actually controls mouse movement, first it will go that particular link and trigger mouse left button and without releasing the left button will go that particular content which needs to be clicked.

I have taken example of Flipkart.com where we get to see the various categories of items when we drag our mouse over the categories links.




package com.flipkart;

import java.io.File;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;

public class flipkart {

void click()
{

File file = new File("C:/IE driver/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver d = new InternetExplorerDriver();
d.get("http://www.flipkart.com");
WebElement M = d.findElement(By.xpath(".//*[@id='fk-header-tab-book']/div[1]/a/div/div// maa[1]/div"));//Main menu
WebElement SM=d.findElement(By.xpath(".//*[@id='fk-header-tab-book']/div[2]/div[1]/div/div/ul[1]/li[1]/a"));//hidden dynamic element




Actions builder = new Actions(d);// To hold mouse on menu
 builder.moveToElement(M).build().perform();
 SM.click();
}
public static void main(String[] args) {
flipkart l= new flipkart();
l.click();//Calling the method

}

}