Skip to main content

Create a Sample selenium java Framework and Project.

1. Create a Sample selenium java Framework and Project.
 
 Step 1. Install TestNg Using Eclipse Marketplace.
 Step 2. Go To
                File-> New -> Other ->
-> Maven ->Maven Project
-> Click Next ->Click on Create a Simple project
-> Click Next
-> Enter Group ID (reverse-domain-packages for groupId)
-> Enter Aritifact ID (project name as artifactId)
-> Click Finish


Now , once Finish You will see the Folder Structure like this.


Step 3: Write Pom.xml then press CTRL+ S
         https://tools-selenium.blogspot.com/2018/08/maven-pomxml-for-java-based-selenium.html



Step 4: Create following package and folders and add all the required drivers .exe file to folder as mentioned in snapshot.


Step 5: Create following Java Class inside CommonFunction package
  1. CommonMethod.java


/**
* @author shashank
*/
package com.projectname.commonfunction;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.Reporter;
import com.projectname.Utils.MarketingPortalUtils;
public class CommonMethod {
WebDriver driver;
WebDriverWait wait;
public boolean isAlreadyLogIn = false;
private final static Logger S_LOGGER = Logger.getLogger(CommonMethod.class.getName());
public CommonMethod(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, 40);
}
// page initializtion for page having more ajax elements
public void SearchResultsPage(WebDriver driver) {
int TimeoutValue = 30;
PageFactory.initElements(new AjaxElementLocatorFactory(driver, TimeoutValue), this);
}
/**
* This method is used to press Tab Key
*/
public void pressTab() {
Actions action = new Actions(this.driver);
action.sendKeys(Keys.TAB).build().perform();
}
/**
* This method is used to press Enter Key
*/
public boolean pressEnter() {
Actions action = new Actions(this.driver);
action.sendKeys(Keys.ENTER).build().perform();
return true;
}
/**
* This method is used to wait for page to be loaded completely before
* executing script
*/
public void waitForPageLoaded() {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString()
.equals("complete");
}
};
try {
wait.until(expectation);
} catch (Throwable error) {
S_LOGGER.error(error.getMessage());
Reporter.log("Timeout waiting for Page Load Request to complete.");
Assert.fail("Timeout waiting for Page Load Request to complete.");
}
}
/**
* This method is used for Explicit Wait until WebElement is visible
*
* @param WebElement
*/
public WebElement waitForElementToBeVisible(WebElement element) {
try {
wait.until(ExpectedConditions.visibilityOf(element));
} catch (Exception e) {
S_LOGGER.error(element + " Element is not visible | " + element + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Assert.fail();
}
return element;
}
/**
* This method is used to verify title of the current page
*
* @param title
*/
public String getTitle(String title) {
try {
S_LOGGER.info("getting title :- " + title);
wait.until(ExpectedConditions.titleIs(title));
//wait.pollingEvery(duration, unit)
} catch (Exception e) {
S_LOGGER.error(title + " title is not visible | " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Assert.fail();
}
return title;
}
/**
* This method is used to take snapshot on test fail
*
* @param driver
* @param result
*/
public static void takeScreenshot(WebDriver driver, ITestResult result) throws Exception {
DateFormat dateFormat = new SimpleDateFormat("MMMMM d yyyy");
Date date = new Date();
System.out.println(dateFormat.format(date));
String current_Time = dateFormat.format(date);
/** This is name of test method, annotated with @Test */
String testMethod = result.getName();
/** This is name of test class, from which, test method has run */
String qualifiedTestClassName = result.getTestClass().toString();
/** This is name of <test> tag of XML */
String testName = result.getTestContext().getName();
try {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
S_LOGGER.info("Screenshot captured");
/**
* Split the qualified Test class name on dot
*/
String[] qualifiedTestClass = qualifiedTestClassName.split("\\.");
/**
* Split the last index on ']' to get the Test class name
*/
String testClass[] = qualifiedTestClass[qualifiedTestClass.length - 1].split("]");
/**
* Saving the screenshot as Test method name in folder with Test
* class name
*/
FileUtils.copyFile(scrFile, new File(SetUP.PATH_SCREENSHOT + testClass[0] + "/" + testMethod + "."
+ testName + "." + current_Time + ".jpg"));
S_LOGGER.info("Screenshot saved to destination");
} catch (Exception e) {
S_LOGGER.error("Screenshot failed. " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Reporter.log("Screenshot could not be captured");
}
}
/**
* This method is used for Explicit Wait until WebElement is clickable
*
* @param WebElement
*/
public WebElement waitForElementToBeClickable(WebElement element) {
try {
wait.until(ExpectedConditions.elementToBeClickable(element));
} catch (Exception e) {
S_LOGGER.error(element + " Element is not clickable | " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Assert.fail();
}
return element;
}
/**
* This method is used for Explicit Wait until WebElement contains specified
* text
*
* @param WebElement
* @param text
*/
public void waitForTextToBePresent(WebElement element, String text) {
try {
wait.until(ExpectedConditions.textToBePresentInElement(element, text));
} catch (Exception e) {
S_LOGGER.error(text + " is not present | " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Assert.fail(text + " is not present");
}
}
/**
* This method is used to switch to new opening tab,verify title and return
* back to previous Tab
*
* @param title
*/
public void switchAndReturnToDefaultWindow(String title) {
this.waitForPageLoaded();
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
this.sleep(1000);
try {
S_LOGGER.info("checking title contains  :- " + title);
wait.until(ExpectedConditions.titleContains(title));
} catch (Exception e) {
S_LOGGER.error("current title does nor contain " + title + " " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
this.sleep(1000);
Assert.fail();
driver.close();
driver.switchTo().window(tabs.get(0));
}
this.sleep(1000);
driver.close();
driver.switchTo().window(tabs.get(0));
}
/**
* This method is used to switch to new opening tab,verify titleContains and
* return back to previous Tab
*
* @param title
* @param Webelemnt
*/
public void openLinkNewTabVerifyTitle(WebElement element, String title) {
Actions newTab = new Actions(driver);
newTab.keyDown(Keys.CONTROL).keyDown(Keys.SHIFT).click(element).keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).build()
.perform();
this.sleep(1000);
S_LOGGER.info(driver.getTitle());
getTitle(title);
this.sleep(1000);
driver.close();
}
/**
* This method is used to switch to new opening tab,verify titleContains and
* return back to previous Tab
*
* @param title
*/
public void verfyTitleContainsOnNewWindow(String title) {
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
this.sleep(1000);
try {
Assert.assertTrue(driver.getTitle().contains(title));
} catch (AssertionError e) {
S_LOGGER.error(e.getMessage() + " title not matched " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Assert.fail();
}
this.sleep(1000);
driver.close();
driver.switchTo().window(tabs.get(0));
}
/**
* This method is used to switch to new tab
*/
public void switchToTab() {
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t");
driver.switchTo().defaultContent();
}
public void switchToTabRightSide() {
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys(Keys.TAB).build().perform();
}
public void switchToTabLeftSide() {
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).keyDown(Keys.SHIFT).sendKeys(Keys.TAB).build().perform();
}
/**
* This method is used find mouse hover color of links
*
* @param WebElement
*/
public void HOVER_COLOR(WebElement ele) {
String HOVER_COLOR;
Actions action = new Actions(driver);
action.moveToElement(ele).build().perform();
com.projectname.Utils.Log.info("after build");
this.waitForElementToBeVisible(ele);
HOVER_COLOR = ele.getCssValue("color");
System.out.println("trying to check hover color " + HOVER_COLOR);
try {
Assert.assertTrue(HOVER_COLOR.equals(MarketingPortalUtils.HOVER_COLOR[0])
|| HOVER_COLOR.equals(MarketingPortalUtils.HOVER_COLOR[1]));
} catch (AssertionError e) {
S_LOGGER.error(e.getMessage() + "  " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
Assert.fail();
}
}
/**
* This method is used to navigate on a particular HTML tag
*
* @param WebElement
*/
public void scrollToElement(WebElement element) {
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("arguments[0].scrollIntoView(true);", element);
}
/**
* This method is used to scroll the webpage in slow motion
*/
public void scrollInSlowMotion() {
for (int second = 0;; second++) {
if (second >= 6) {
break;
}
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,300)", ""); // y
this.sleep(3000);
}
}
/**
* This method is used to scroll the webpage to top
*/
public void scrollToTop() {
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-3000)", "");
this.sleep(3000);
}
/**
* This method is used to generate random password
*/
public String generatePassword() {
final String UPPERCHAR_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ@!#$%^";
final String SPECIALCHAR_STRING = "@!#$%^";
final String LOWERCHAR_STRING = "abcdefghijklmnopqrstuvwxyz";
final String INTEGER_STRING = "0123456789";
int count = 10;
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int) (Math.random() * UPPERCHAR_STRING.length());
builder.append(UPPERCHAR_STRING.charAt(character));
}
builder.append(SPECIALCHAR_STRING.charAt((int) (Math.random() * SPECIALCHAR_STRING.length())))
.append(LOWERCHAR_STRING.charAt((int) (Math.random() * LOWERCHAR_STRING.length())))
.append(INTEGER_STRING.charAt((int) (Math.random() * INTEGER_STRING.length())));
S_LOGGER.info("password is:-  " + builder.toString());
return builder.toString();
}
/**
* This method is used to generate randomly user name
*/
public String generateUserName() {
final String UPPERCHAR_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
final String SPECIALCHAR_STRING = "@!#$%^";
final String LOWERCHAR_STRING = "abcdefghijklmnopqrstuvwxyz";
final String INTEGER_STRING = "0123456789";
int count = 8;
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int) (Math.random() * UPPERCHAR_STRING.length());
builder.append(UPPERCHAR_STRING.charAt(character));
}
builder.append(SPECIALCHAR_STRING.charAt((int) (Math.random() * SPECIALCHAR_STRING.length())))
.append(LOWERCHAR_STRING.charAt((int) (Math.random() * LOWERCHAR_STRING.length())))
.append(INTEGER_STRING.charAt((int) (Math.random() * INTEGER_STRING.length())));
return builder.toString();
}
/**
* This method is used to generate names like fname lname
*/
public String generateName() {
final String UPPERCHAR_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int count = 8;
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int) (Math.random() * UPPERCHAR_STRING.length());
builder.append(UPPERCHAR_STRING.charAt(character));
}
return builder.toString();
}
/**
* This method is used to generate Email using spoofing concept
*
* @param gmailIDWithoutDomain
*/
public String generateEmail(String mailID) {
final String digits = "02135468790123";
int count = 4;
StringBuilder builder = new StringBuilder();
builder.append(mailID).append("+");
while (count-- != 0) {
int character = (int) (Math.random() * digits.length());
builder.append(digits.charAt(character));
}
builder.append("@gmail.com");
System.out.println("Email is:-  " + builder.toString());
return builder.toString();
}
/**
* Password validation logic covered below
*/
/**
* it checks string have three consecutive chars like 123,abc
*/
public boolean containConsecutiveChars(String password) {
String regex = ".*(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|ABC|BCD|CDE|DEF|EFG|FGH|GHI|HIJ|IJK|JKL|KLM|LMN|MNO|NOP|OPQ|PQR|QRS|RST|STU|TUV|UVW|VWX|WXY|XYZ|012|123|234|345|456|567|678|789).*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.find();
}
/**
* it checks string have numeric value
*/
public boolean containsNumber(String password) {
String regex = ".*\\d.*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.find();
}
/**
* it checks string have at least one special chars
*/
public boolean containsSpecialChar(String password) {
String regex = ".*[!@#$%^&*].*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.find();
}
/**
* it checks string have three consecutive chars like 123,abc
*/
public boolean containsAtleastOneUpperChar(String password) {
String regex = ".*[A-Z].*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.find();
}
/**
* it checks string have at least one lower char
*/
public boolean containsAtleastOneLowerChar(String password) {
String regex = ".*[a-z].*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.find();
}
/**
* it checks password contains username
*/
public boolean containsUserName(String password, String userName) {
return password.contains(userName);
}
/**
* it checks string have three consecutive chars like aaa
*/
public boolean consecutiveSimilarChars(String password) {
String regex = "([a-zA-Z0-9])\\1\\1";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(password);
return match.find();
}
public void logIn(String userName, String password) {
if (!isAlreadyLogIn) {
driver.findElement(By.xpath("//*[@id='email']")).sendKeys(userName);
driver.findElement(By.xpath("//*[@id='pass']")).sendKeys(password);
driver.findElement(By.xpath("//*[@id='loginbutton']")).click();
isAlreadyLogIn = true;
}
}
/**
* this method is used to verify max lenth of input fields that textbox can
* contain
*/
public int maxLengthOfInputField(WebElement ele) {
String text = this.waitForElementToBeVisible(ele).getAttribute("value");
int size = text.length();
System.out.println(size + " in size and text inside textbox " + text);
return size;
}
public void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* This method is used to check whether the field is empty or not.
*
* @param element
*            it is used to pass the element locator
*/
public void checkTextBoxEmpty(WebElement element) {
if (element.getText().equals("")) {
S_LOGGER.info(element + "Field is empty :: Success");
} else {
S_LOGGER.error(element + "Field is not empty :: Failure");
Assert.fail(element + "Field is not empty :: Failure");
}
}
/**
* This method is used to check whether the drop down is selected or not.
*/
public void checkDropDown(WebElement element) {
Select select = new Select(element);
if (select.getFirstSelectedOption().getText().equals("Select")) {
S_LOGGER.info(element + "Dropdown is not selectd");
} else {
S_LOGGER.error(element + "Dropdown is selected :: Failed");
Assert.fail(element + "Dropdown is selected :: Failed");
}
}
/**
* This method is used to check whether the radio button is selected or not.
*/
public void checkRadioButton(WebElement element) {
if (!element.isSelected()) {
S_LOGGER.info(element + "Radio button is not selected");
} else {
S_LOGGER.error(element + "Radio button is selected  :: Failure");
Assert.fail(element + "Radio button is selected  :: Failure");
}
}
/**
* This method is used to generate 10 digit random number.
*/
public int randomNumber() {
Random randomNum = new Random();
int randomNum1 = randomNum.nextInt();
return randomNum1;
}
/**
* click on logut link
*
* @parm logout locator string from util
*/
public void clickOnLogout() {
waitForElementToBeVisible(driver.findElement(By.xpath(MarketingPortalUtils.LOGOUT_LINK))).click();
}
/**
* click on Login link
*
* @parm login locator string from util
*/
public void clickOnLogin() {
waitForElementToBeVisible(driver.findElement(By.cssSelector(MarketingPortalUtils.LOGIN_LINK))).click();
}
/**
* click on register link
*
* @parm register locator string from RegisterutilFile
*/
public void clickOnRegister() {
waitForElementToBeVisible(driver.findElement(By.cssSelector(MarketingPortalUtils.REGISTER_LINK))).click();
}
public WebElement waitForElementToBeClickable1(By locator) {
S_LOGGER.debug("waitForElementToBeClickable locator (" + locator.toString() + ")");
long waitForElementPresentTimeout = 60;
WebDriverWait webDriverWait = new WebDriverWait(driver, waitForElementPresentTimeout);
return webDriverWait.ignoring(NoSuchElementException.class)
.until(ExpectedConditions.elementToBeClickable(locator));
}
/**
* it is used to close the browser
*/
public void tearDown() {
try {
driver.close();
S_LOGGER.info("browser closed");
} catch (Exception e) {
driver.quit();
e.getStackTrace();
S_LOGGER.info("browser quitted");
Reporter.log("Browser window is closed");
}
}
}


b.  ExtenttestNGIReporterListener.java


package com.projectname.commonfunction;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.xml.XmlSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentTestNGIReporterListener implements IReporter {
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "Extent.html";
private ExtentReports extent;
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getFailedTests(), Status.FAIL);
buildTestNodes(context.getSkippedTests(), Status.SKIP);
buildTestNodes(context.getPassedTests(), Status.PASS);
}
}
for (String s : Reporter.getOutput()) {
extent.setTestRunnerOutput(s);
}
extent.flush();
}
private void init() {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
htmlReporter.config().setDocumentTitle("ExtentReports - Created by TestNG Listener");
htmlReporter.config().setReportName("ExtentReports - Created by TestNG Listener");
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setTheme(Theme.STANDARD);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
}
private void buildTestNodes(IResultMap tests, Status status) {
ExtentTest test;
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.createTest(result.getMethod().getMethodName());
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
} else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}


C. TestListners.java


package com.projectname.commonfunction;
import java.util.Date;
import org.apache.log4j.Logger;
import org.testng.IExecutionListener;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;
public class TestListener implements IExecutionListener, ISuiteListener, ITestListener {
private static Logger S_LOGGER = Logger.getLogger(TestListener.class.getName());
public void onExecutionStart() {
Date date = new Date();
}
public void onExecutionFinish() {
}
public void onStart(ISuite suite) {
S_LOGGER.info(suite.getName() + " is going to be executed ");
}
public void onFinish(ISuite suite) {
S_LOGGER.info(suite.getName() + " has executed");
}
public void onTestStart(ITestResult result) {
S_LOGGER.info(result.getTestClass().getName() + " ***** " + result.getMethod().getMethodName() + " STARTS" + " ***** ");
}
public void onTestSuccess(ITestResult result) {
S_LOGGER.info("PASS");
Reporter.log(result.getTestClass().getName() + " -> " + result.getMethod().getMethodName() + ": PASS");
}
public void onTestFailure(ITestResult result) {
result.getInstanceName();
S_LOGGER.error("FAIL");
Reporter.log(result.getTestClass().getName() + " -> " + result.getMethod().getMethodName() + ": FAIL");
}
public void onTestSkipped(ITestResult result) {
S_LOGGER.error("SKIPPED");
Reporter.log(result.getTestClass().getName() + " -> " + result.getMethod().getMethodName() + ": SKIPPED");
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onStart(ITestContext context) {
S_LOGGER.info("********** " + context.getName() + " STARTS **********");
}
public void onFinish(ITestContext context) {
S_LOGGER.info("********** " + context.getName() + " END   " + " **********");
}
}












D. SetUp.java


package com.projectname.commonfunction;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.Reporter;
public class SetUP {
private final static Logger S_LOGGER = Logger.getLogger(SetUP.class.getName());
static WebDriver driver;
static String s = File.separator;
//You can also below String constant inside Constant.java in Utils package.
final static String BASE_PATH = new File("").getAbsolutePath();
final static String WIN_CHROME = BASE_PATH + s + "src" + s + "test" + s + "resources" + s + "windows" + s
+ "chromedriver.exe";
final static String WIN_FIREFOX = BASE_PATH + s + "src" + s + "test" + s + "resources" + s + "windows" + s
+ "geckodriver.exe";
final static String WIN_IE = BASE_PATH + "/src/test/resources/windows/IEDriverServer.exe";
final static String LINUX_CHROME = BASE_PATH + "/src/test/resources/linux/chromedriver";
final static String LINUX_FIREFOX = BASE_PATH + "/src/test/resources/linux/geckodriver";
final static String MAC_CHROME = BASE_PATH + "/src/test/resources/mac/chromedriver";
final static String MAC_FIREFOX = BASE_PATH + "/src/test/resources/mac/geckodriver";
final static String PROPERTIES_FILE = BASE_PATH + "/src/test/resources/files/path.properties";
public static final String PATH_SCREENSHOT = BASE_PATH + "/screenshot/";
public final static String EXCELFILEPATH = BASE_PATH + "/src/test/resources/files/TestData.xlsx";
public static String operatingSystem() {
S_LOGGER.info(System.getProperty("os.name"));
if (System.getProperty("os.name").toLowerCase().contains("win")) {
return "win";
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
return "mac";
} else if (System.getProperty("os.name").toLowerCase().contains("nux")
|| System.getProperty("os.name").toLowerCase().contains("nix")) {
return "lin";
} else
return "unsuppotable os to selenium";
}
/**
* This method is used to read properties file
*
* @param Key
* @throws IOException
*/
public static String getUrl(String BASEURL) throws IOException {
String URL = null;
FileInputStream fileInput = null;
Properties prop = new Properties();
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
InputStream propertiesStream = contextClassLoader.getResourceAsStream("resources/files/path.properties");
try {
File file = new File(PROPERTIES_FILE);
fileInput = new FileInputStream(file);
prop.load(fileInput);
URL = prop.getProperty(BASEURL).toString();
} catch (FileNotFoundException e) {
try {
prop.load(propertiesStream);
URL = prop.getProperty(BASEURL).toString();
} catch (IOException e1) {
S_LOGGER.error("unable to pass URL to the browser");
Reporter.log("URL has not loaded from properties file");
e1.printStackTrace();
}
}
finally {
if (propertiesStream != null) {
propertiesStream.close();
}
if (fileInput != null) {
fileInput.close();
}
}
return URL;
}
/**
* This method is used to launch browser based on value coming from XML file
*
* @param browser
*
*/
public static WebDriver setUP(String browser) {
DOMConfigurator.configure("Log4j.xml");
com.projectname.Utils.Log.startTestCase(browser.toUpperCase());
if (operatingSystem().equals("win")) {
if (browser.equals("FFX")) {
S_LOGGER.info(WIN_FIREFOX);
System.setProperty("webdriver.gecko.driver", WIN_FIREFOX);
S_LOGGER.info("Test Starts Running In Firefox Browser.");
driver = new FirefoxDriver();
manageBrowser(driver);
return driver;
} else if (browser.equals("CRM")) {
System.setProperty("webdriver.chrome.driver", WIN_CHROME);
driver = new ChromeDriver();
manageBrowser(driver);
S_LOGGER.info("Test Starts Running In Google chrome.");
return driver;
} else if (browser.equals("IE")) {
S_LOGGER.info("Test Starts Running In IE.");
System.setProperty("webdriver.ie.driver", WIN_IE);
driver = new InternetExplorerDriver();
manageBrowser(driver);
return driver;
} else {
S_LOGGER.info("please pass correct  browser value ");
}
} else if (operatingSystem().equals("lin")) {
if (browser.equals("FFX")) {
System.setProperty("webdriver.gecko.driver", LINUX_FIREFOX);
S_LOGGER.info("Test Starts Running In Firefox Browser.");
driver = new FirefoxDriver();
manageBrowser(driver);
return driver;
} else if (browser.equals("CRM")) {
System.setProperty("webdriver.chrome.driver", LINUX_CHROME);
driver = new ChromeDriver();
manageBrowser(driver);
return driver;
} else {
System.setProperty("webdriver.chrome.driver", LINUX_CHROME);
S_LOGGER.info("Test Starts Running In Google chrome.");
driver = new ChromeDriver();
manageBrowser(driver);
return driver;
}
} else if (operatingSystem().equals("mac")) {
if (browser.equals("FFX")) {
System.setProperty("webdriver.gecko.driver", MAC_FIREFOX);
S_LOGGER.info("Test Starts Running In Firefox Browser.");
driver = new FirefoxDriver();
manageBrowser(driver);
return driver;
} else if (browser.equals("CRM")) {
System.setProperty("webdriver.chrome.driver", MAC_CHROME);
driver = new ChromeDriver();
manageBrowser(driver);
return driver;
} else if (browser.equals("SF")) {
DesiredCapabilities safariCap = DesiredCapabilities.safari();
S_LOGGER.info("Test Starts Running In safari.");
driver = new SafariDriver(safariCap);
manageBrowser(driver);
return driver;
}
} else {
S_LOGGER.info(operatingSystem() + " supports win linux mac");
}
return driver;
}
/**
* This method is used to maximize browser and load url from properties file
*
* @param driver
* @param BASEURL
*/
public static void manageBrowser(WebDriver driver) {
S_LOGGER.info(s + "sha");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
S_LOGGER.info("Implicit wait applied on the driver for 60 seconds");
driver.manage().window().maximize();
S_LOGGER.info("Browser window is maximized");
try {
driver.get(getUrl("BASEURL"));
driver.get(
S_LOGGER.info(getUrl("BASEURL"));
Reporter.log("Web application launched successfully");
} catch (Exception e) {
S_LOGGER.error("Web application launch failure | " + new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
S_LOGGER.debug(e.getMessage());
}
}
}


Step 6 :  Download All the driver.exe and put it under src/test/resources as below









Step 7.
  1. Create Log.java class under Utils package


package com.projectname.Utils;
import org.apache.log4j.Logger;
public class Log {
// Initialize Log4j logs
private static Logger S_LOGGER = Logger.getLogger(Log.class.getName());
// This is to print log for the beginning of the test case, as we usually run so many test cases as a test suite
public static void startTestCase(String sTestCaseName){
S_LOGGER.info("                                                                ");
S_LOGGER.info("****************************************************************");
S_LOGGER.info("****************************************************************");
S_LOGGER.info("$$$$$$$$$$$$$$$$$$$$$       "+sTestCaseName+ "       $$$$$$$$$$$$$$$$$$$$$$$$$");
S_LOGGER.info("****************************************************************");
S_LOGGER.info("****************************************************************");
}
//This is to print log for the ending of the test case
public static void endTestCase(String sTestCaseName){
S_LOGGER.info("XXXXXXXXXXXXXXXX    " + "-E---N---D-"+"    XXXXXXXXXXXXXXXX");
S_LOGGER.info("X");
S_LOGGER.info("X");
S_LOGGER.info("X");
S_LOGGER.info("X");
}
// Need to create these methods, so that they can be called
public static void info(String message) {
S_LOGGER.info(message);
}
public static void warn(String message) {
S_LOGGER.warn(message);
}
public static void error(String message) {
S_LOGGER.error(message);
}
public static void fatal(String message) {
S_LOGGER.fatal(message);
}
public static void debug(String message) {
S_LOGGER.debug(message);
}
}


B. Create constants.java under Utils package.
 You can put all your Constant variable inside this class


Step 8. Craete SampleLogin.java Class under myaccount package
  1. The following code is based on Pagefactory which advance model of page object model.
package com.projectname.myaccount;
import org.apache.log4j.Logger;
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.PageFactory;
import com.projectname.commonfunction.CommonMethod;
public class SampleLogin {
private final static Logger S_LOGGER =    Logger.getLogger(SampleLogin.class.getName());
WebDriver driver;
CommonMethod cp;
// Webelements
@FindBy(how = How.ID, using = "Sign In")
private WebElement signIn;
@FindBy(how = How.NAME, using = "lpasswd")
private WebElement pwd;
@FindBy(how = How.NAME, using = "luser")
private WebElement userName;
public SampleLogin(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
cp = new CommonMethod(driver);
}
public void login(){
userName.sendKeys("shashank");
pwd.sendKeys("shahsank");
signIn.click();
}


}
B. Create a SampleTest Class under myaccounttest package
package com.projectname.myaccounttest;


import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.projectname.marketingportal.SampleLogin;
import com.projectname.commonfunction.CommonMethod;
import com.projectname.commonfunction.FindBrokenLinks;
import com.projectname.commonfunction.SetUP;


@Listeners(com.projectname.commonfunction.ExtentTestNGIReporterListener.class)  
class SampleTest {


private final static Logger S_LOGGER = Logger.getLogger(SampleTest.class.getName());
static WebDriver driver;
SampleLogin login;
CommonMethod cp;


@BeforeTest
@Parameters({ "browser" })
private void setUp(@Optional("FFX") String browser) {
S_LOGGER.info("HomePageTest S_LOGGER is running");
try{
SampleTest.driver = SetUP.setUP(browser);


} catch (Exception e) {
S_LOGGER.info("setUp() method has not executed successfully");
S_LOGGER.error("setUp() method has not executed successfully  | "
+ new Object() {
}.getClass().toString() + " | method " + new Object() {
}.getClass().getEnclosingMethod().getName());
Reporter.log("setUp() method has not executed successfully");
}
cp = new CommonMethod(driver);
cp.waitForPageLoaded();
login=new SampleLogin(driver);
}
/**
/**
* This method runs after all the Test scenarios have run. It closes the
* browser
*/
@AfterClass
public void teardown() throws InterruptedException {
cp.tearDown();
S_LOGGER.info("Browser window is closed");
Reporter.log("Browser window is closed");
}
/**
* This method runs after  EachTest Method scenarios have run. It takes
* snapshot where test has failed.
*/
@AfterMethod
public void afterTestMethod(ITestResult result) throws Exception{
if(!result.isSuccess()){
CommonMethod.takeScreenshot(SampleTest.driver, result);
}
}


@Test( priority = 1)
private void loginTest() {
S_LOGGER.info("headerLogoTest started");
SampleLogin.login();
}










Step-9 Create log4j.xml inside project and place the below lines of code .
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<appender name="file" class="org.apache.log4j.FileAppender">
<param name="Threshold" value="INFO" />
<param name="File" value="target/test.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="[%d{MM-dd-yyyy HH:mm:ss}] [%-5p] [%60c] [%25M] %m%n" />
</layout>
</appender>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<param name="Threshold" value="INFO" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern"
value="[%d{MM-dd-yyyy HH:mm:ss}] [%-5p] [%60c] [%25M] %m%n" />
</layout>
</appender>
<root>
<priority value="TRACE" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</log4j:configuration>


Step 10: Create a testNG.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" thread-count="1">
<test name="Test In FireFox">
<parameter name="browser" value="FFX" />
<classes>
<class name="com.projectname.myaccounttest.SampleLogin"/>
</classes>
</test> <!-- Test -->
<test name="Test In Chrome">
<parameter name="browser" value="CRM" />
<classes>
<class name="com.projectname.myaccounttest.SampleLogin"/>
</classes>
</test> <!-- Test -->
<test name="Test In IE">
<parameter name="browser" value="IE" />
<classes>
<class name="com.projectname.myaccounttest.SampleLogin"/>
</classes>
</test> <!-- Test -->
<test name="Test In safari">
<parameter name="browser" value="SF" />
<classes>
<class name="com.projectname.myaccounttest.SampleLogin"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->


Step 11: Run the POM.xml as maven install or maven build.
Step 12: Run testNG.xml as testNG SUite.


Comments