Wednesday, May 29, 2019
Thursday, May 16, 2019
Finding element ByChained using chained class
DOM Looks like this for Google Search button
package secondpackage;
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.support.pagefactory.ByChained;
public class DimensionTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mitturaj.h\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.com/");
driver.manage().window().maximize();
driver.findElement(By.name("q")).sendKeys("Karnataka");
WebElement element = driver
.findElement(new ByChained(By.xpath("//div[@class='FPdoLc VlcLAe']"), By.name("btnK")));
element.click();
}
}
Other ways is put in the List and click on the second element
List<WebElement> searchElements = driver.findElements(By.name("btnK"));
Highlight element in Selenium java
package secondpackage;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class DimensionTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mitturaj.h\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.com/");
driver.manage().window().maximize();
List<WebElement> searchElements = driver.findElements(By.name("btnK"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].style.border='3px solid red'", searchElements.get(1));
}
}
Output:
Set Dimension of window in Selenium Java
package secondpackage;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DimensionTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mitturaj.h\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.com/");
System.out.println(driver.manage().window().getSize());
Dimension dimension = new Dimension(500, 500);
driver.manage().window().setSize(dimension);
System.out.println(driver.manage().window().getSize());
}
}
Output
(945, 1020)
(500, 500)
Thursday, May 9, 2019
Wednesday, May 8, 2019
Tuesday, May 7, 2019
Data driven testing in selenium by using CSV file and TestNG
CSV file looks like this 😉
Sachin,Tendulkar,India
Ricky,Ponting,Australia
Java class to fetch from row wise 😎
package csv;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class CsvFiles1 {
static String filePath = "C:\\Users\\Mitturaj.h\\Desktop\\customers.csv";
static BufferedReader bufferedReader = null;
static String line = "";
static String[][] players;
static int rows = 0;
private static String[][] getdata() {
try {
players = new String[2][3];
bufferedReader = new BufferedReader(new FileReader(filePath));
while ((line = bufferedReader.readLine()) != null) {
String[] country = line.split(",");
// this will determine number of columns in the csv file after
// spitting by commas
System.out.println("Number columns " + country.length);
for (int x = 0; x < country.length; x++) {
players[rows][x] = country[x];
}
System.out.println(country[1]);
rows++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("number of the rows in the columns " + rows);
return players;
}
@DataProvider(name = "data")
public static Object[][] getPlayers() {
return getdata();
}
@Test(dataProvider = "data")
public void testPlayers(String fname, String lname, String country) {
System.out.println(fname + " " + lname + " " + country);
}
}
Let me know what you thing, Happy coding! 🙌🙌
Data driven testing in selenium by using CSV file and TestNG
Here is the CSV File
Java class to retrieve data from the CSV file and create data provider out of it😉
Let me know what you think in the comment 🤞, Happy coding🙌🙌
Sachin Tendulkar India
Ricky Ponting Australia
Java class to retrieve data from the CSV file and create data provider out of it😉
package csv;
import java.io.DataInputStream;
import java.io.FileInputStream;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class CsvFiles {
private static String line;
static int row;
static int cols;
static String[][] customers;
/*
* Retrieve data from the CSV file and return it has String two dimensional
* String array
*/
private static String[][] getdata() throws Exception {
String filePath = "C:\\Users\\Mitturaj.h\\Desktop\\customers.csv";
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(filePath));
/*
* initialized the array and give size of the columns and rows for CSV
* file data
*/
customers = new String[2][3];
/* ReadLine() method is deprecated now, will need to find alternative
for this one ;)*/
while ((line = dataInputStream.readLine()) != null) {
String[] data = line.split(",");
// can find number of columns after splitting by comma
int cols = data.length;
for (int x = 0; x < cols; x++) {
customers[row][x] = data[x];
}
// can find rows numbers by iterating the row variable ;)
row++;
}
return customers;
}
@DataProvider(name = "data")
public static Object[][] getdataprovider() throws Exception {
return getdata();
}
@Test(dataProvider = "data")
public void show(String fname, String lname, String city) {
System.out.println(fname + " " + lname + " " + city);
}
}
Let me know what you think in the comment 🤞, Happy coding🙌🙌
Sunday, May 5, 2019
Simple log4j example by using xml file in Java
copy log4j2.xml in resource folder
create a logger in your class
Here is the class
add these 2 dependencies in POM.xml file
your log file looks like below:)
Let me know what you think in the comment:) Happy coding!
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<!-- Console Appender -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<!-- Rolling File Appender -->
<RollingFile name="RollingFile">
<FileName>C:/Users/Mutturaj/workspace/ExtentReports/log/mylog.log</FileName>
<FilePattern>C:/log/size-based-logs/%d{yyyy-MM-dd-hh}-%i.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 KB" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
</Appenders>
<Loggers>
<Logger name="extentReportForMultipleTestsInAClass" level="debug" additivity="false">
<AppenderRef ref="RollingFile" />
<AppenderRef ref="Console" />
</Logger>
<Root level="trace">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
create a logger in your class
private static final Logger log=LogManager.getLogger(ClassA.class);
Here is the class
package extentReportForMultipleTestsInAClass;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ClassA extends BaseTest {
private static final Logger log=LogManager.getLogger(ClassA.class);
@Test
public void method1() {
log.info("Method 1 started");
test = extent.createTest("method1");
driver.get("https://www.facebook.com/");
String title = driver.getTitle();
System.out.println(title);
log.info(title);
Assert.assertEquals(title, "Facebook – log");
}
@Test
public void method2() {
log.info("Method 2 started");
test = extent.createTest("method1");
driver.get("https://www.facebook.com/");
String title = driver.getTitle();
System.out.println(title);
log.info(title);
Assert.assertEquals(title, "Facebook – log");
}
}
add these 2 dependencies in POM.xml file
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
your log file looks like below:)
2019-May-05 11:13:03 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Method 1 started
2019-May-05 11:13:06 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Facebook – log in or sign up
2019-May-05 11:13:12 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Method 2 started
2019-May-05 11:13:15 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Facebook – log in or sign up
2019-May-05 11:15:43 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Method 1 started
2019-May-05 11:15:47 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Facebook – log in or sign up
2019-May-05 11:15:53 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Method 2 started
2019-May-05 11:15:57 AM [main] INFO extentReportForMultipleTestsInAClass.ClassA - Facebook – log in or sign up
2019-May-05 11:16:03 AM [main] INFO extentReportForMultipleTestsInAClass.ClassB - Method 1 started
Let me know what you think in the comment:) Happy coding!
Attache screenshot to the failed tests in extent report 3
package extentReportForMultipleTestsInAClass;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
public class BaseTest implements ITestListener {
public WebDriver driver;
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest test;
@BeforeTest
public void setUp() {
getReport();
}
@BeforeMethod
public void launchBrowser() {
getDriver();
}
@AfterMethod
public void closeDriver(ITestResult result) throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
test.fail("sanpshot below: " + test.addScreenCaptureFromPath(takeScreenShot(driver)));
}
driver.quit();
}
@AfterTest
public void tearDown() {
extent.flush();
}
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
test.log(Status.PASS, MarkupHelper.createLabel(result.getName() + " Test Case PASSED", ExtentColor.GREEN));
}
public void onTestFailure(ITestResult result) {
test.log(Status.FAIL,
MarkupHelper.createLabel(result.getName() + " Test case FAILED due to below issues:", ExtentColor.RED));
test.fail(result.getThrowable());
}
public String takeScreenShot(WebDriver driver) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
String date = dateFormat.format(new Date());
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// The below method will save the screen shot in d drive with test
// method name
String destination = "C:/Users/Mutturaj/workspace/ExtentReports/" + date + ".png";
try {
FileUtils.copyFile(scrFile, new File(destination));
} catch (IOException e) {
e.printStackTrace();
}
return destination;
}
public void onTestSkipped(ITestResult result) {
test.log(Status.SKIP, MarkupHelper.createLabel(result.getName() + " Test Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onStart(ITestContext context) {
}
public void onFinish(ITestContext context) {
}
public static void getReport() {
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") + "/test-output/MyReport.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "Windows 10");
extent.setSystemInfo("Host Name", "Test");
extent.setSystemInfo("Environment", "QA");
extent.setSystemInfo("QA Name", "Mutturaj Hulagabal");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("Extent report");
htmlReporter.config().setReportName("Final Report");
}
public WebDriver getDriver() {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
}
package extentReportForMultipleTestsInAClass;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ClassA extends BaseTest {
@Test
public void method1() {
test = extent.createTest("class A1");
driver.get("https://www.facebook.com/");
String title = driver.getTitle();
System.out.println(title);
Assert.assertEquals(title, "Facebook – log");
}
@Test
public void method2() {
test = extent.createTest("class A1");
driver.get("https://www.facebook.com/");
String title = driver.getTitle();
System.out.println(title);
Assert.assertEquals(title, "Facebook – log");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listener class-name="extentReportForMultipleTestsInAClass.BaseTest"/>
</listeners>
<test thread-count="5" name="Test1">
<classes>
<class name="extentReportForMultipleTestsInAClass.ClassA" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Saturday, May 4, 2019
Extent report for multiple classes
pom.xml
Base class
Tow test classes
TestNG.ml file
Let me know what you think in the comment :) Happy coding!
<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.extentreport</groupId>
<artifactId>practice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
</project>
Base class
package extentReportForMultipleTestsInAClass;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
public class BaseTest implements ITestListener {
public WebDriver driver;
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest test;
@BeforeTest
public void setUp() {
getReport();
}
@AfterTest
public void tearDown() {
extent.flush();
}
@AfterMethod
public void closeDriver() {
driver.quit();
}
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
test.log(Status.PASS, MarkupHelper.createLabel(result.getName() + " Test Case PASSED", ExtentColor.GREEN));
}
public void onTestFailure(ITestResult result) {
test.log(Status.FAIL,
MarkupHelper.createLabel(result.getName() + " Test case FAILED due to below issues:", ExtentColor.RED));
test.fail(result.getThrowable());
}
public void onTestSkipped(ITestResult result) {
test.log(Status.SKIP, MarkupHelper.createLabel(result.getName() + " Test Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onStart(ITestContext context) {
}
public void onFinish(ITestContext context) {
}
public static void getReport() {
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") + "/test-output/MyReport.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "Windows 10");
extent.setSystemInfo("Host Name", "Test");
extent.setSystemInfo("Environment", "QA");
extent.setSystemInfo("QA Name", "Mutturaj Hulagabal");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("Extent report");
htmlReporter.config().setReportName("Final Report");
}
}
Tow test classes
package extentReportForMultipleTestsInAClass;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.Test;
public class ClassA extends BaseTest {
@Test
public void classB1() {
test = extent.createTest("class A1");
driver.get("https://www.facebook.com/");
Assert.assertTrue(true);
}
@Test
public void classB2() {
test = extent.createTest("class A2");
Assert.assertTrue(false);
}
@Test
public void classB3() {
test = extent.createTest("class A3");
throw new SkipException("Skipped");
}
}
package extentReportForMultipleTestsInAClass;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ClassB extends BaseTest {
@Test
public void classB1() {
test=extent.createTest("class B");
driver.get("https://www.facebook.com/");
test.info(driver.getTitle());
Assert.assertTrue(true);
}
@Test
public void classB2() {
test=extent.createTest("class B");
Assert.assertTrue(false);
}
}
TestNG.ml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listener class-name="extentReportForMultipleTestsInAClass.BaseTest"/>
</listeners>
<test thread-count="5" name="Test1">
<classes>
<class name="extentReportForMultipleTestsInAClass.ClassA" />
<class name="extentReportForMultipleTestsInAClass.ClassB" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Let me know what you think in the comment :) Happy coding!
Subscribe to:
Posts (Atom)