Tuesday, July 30, 2019

Configure Log4j in Java by using properties/xml file

Put log4j.xml or log4j.xml file in the resource folder


2019-07-30 16:00:09 DEBUG Log4jXmlConfigurationExample:18 - Log4j appender configuration is successful !!
# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to console
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
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\Users\\diya-mutturajh\\test123\\Logs\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
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
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console"
class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<appender name="fileAppender"
class="org.apache.log4j.RollingFileAppender">
<param name="File" value="demoApplication.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="console"></appender-ref>
<appender-ref ref="fileAppender"></appender-ref>
</root>
</log4j:configuration>
view raw log4j.xml hosted with ❤ by GitHub
package test1231;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
public class Log4JExample
{
static Logger logger = Logger.getLogger(Log4JExample.class);
public static void main(String[] args)
{
//DOMConfigurator is used to configure logger from xml configuration file
DOMConfigurator.configure("C:\\Users\\mutturajh\\test123\\src\\test\\java\\test1231\\log4j.xml");
//Log in console in and log file
logger.debug("Log4j appender configuration is successful !!");
}
}

Thursday, July 11, 2019

API testing by using Fluent API HTTP client

some important imports https://hulagabal.blogspot.com/2019/07/rest-assured-pom-file-and-imports.html
Dependency to be used
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.1</version>
</dependency>
package newresrapi;
import java.io.IOException;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.path.json.JsonPath;
public class HTTPTest {
@Test
public void getFluently() throws ClientProtocolException, IOException {
// Get request
String entity = Request.Get("http://dummy.restapiexample.com/api/v1/employee/5928").execute().returnContent()
.asString();
System.out.println("---------Get started---------");
System.out.println(entity);
System.out.println(new JsonPath(entity).get("id"));
System.out.println("---------Get End---------");
}
@Test
public void putFluently() throws ClientProtocolException, IOException {
// Put request
String updateresponse = Request.Put("http://dummy.restapiexample.com/api/v1/update/5928")
.bodyString("{\"name\":\"muu222\",\"salary\":\"1123\",\"age\":\"14\"}", ContentType.APPLICATION_JSON)
.execute().returnContent().asString();
System.out.println("--------------Put started-------------");
System.out.println(updateresponse);
System.out.println("--------------Put End-------------");
}
}
view raw HTTPTest.java hosted with ❤ by GitHub

Tuesday, July 9, 2019

All Rest Assured operation in one


package test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.util.JSONPObject;
import io.restassured.http.ContentType;
import io.restassured.http.Cookie;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.internal.path.json.mapping.JsonObjectDeserializer;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.response.ValidatableResponse;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.XmlConfig;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matcher;
import io.restassured.matcher.ResponseAwareMatcher;
import io.restassured.matcher.RestAssuredMatchers.*;
import io.restassured.matcher.ResponseAwareMatcherComposer.*;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.specification.ResponseSpecification;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import io.restassured.mapper.ObjectMapperType;
import static io.restassured.path.json.JsonPath.*;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import static org.hamcrest.Matchers.*;
public class AllRestAPIOperations {
ResponseBody<?> responseBody;
String id;
@Test
public void allInOne() {
String name = "muttu1111111";
// Post request creating employee
responseBody = given().accept(ContentType.JSON)
.body("{\"name\":\"" + name + "\",\"salary\":\"123\",\"age\":\"23\"}").when()
.post("http://dummy.restapiexample.com/api/v1/create").body();
id = responseBody.jsonPath().getString("id");
String salary = "233"; //Salary amount needs be updated
// Put request- Update salary for the above employee
responseBody = given().accept(ContentType.JSON)
.body("{\"name\":\"" + name + "\",\"salary\":\"" + salary + "\",\"age\":\"23\"}").when()
.put("http://dummy.restapiexample.com/api/v1/update/" + id).body();
salary = responseBody.jsonPath().getString("salary");
System.out.println(id + " " + salary);
// Get request after updating the salary- fetch the details of an employee
String body = when().get("http://dummy.restapiexample.com/api/v1/employee/" + id + "").body().asString();
System.out.println(body);
// Delete Employee by id
String as = when().delete("http://dummy.restapiexample.com/api/v1/delete/" + id).asString();
System.out.println(as);
}
}

Sunday, July 7, 2019

Rest assured pom file and imports


<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.hulagabal.rest</groupId>
<artifactId>com.hulagabal.rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.2</version>
<scope>test</scope>
</dependency>
<!-- used to parse Json Document -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>3.0.2</version>
</dependency>
<!-- to validate that a JSON response conforms to a Json Schema -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.0.2</version>
</dependency>
<!-- used to parse xml document -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>3.0.2</version>
</dependency>
<!-- junit/testng can be used -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
</dependency>
</dependencies>
</project>
//imports
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.http.ContentType;
import io.restassured.http.Cookie;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.internal.path.json.mapping.JsonObjectDeserializer;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.response.ValidatableResponse;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.XmlConfig;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matcher;
import io.restassured.matcher.ResponseAwareMatcher;
import io.restassured.matcher.RestAssuredMatchers.*;
import io.restassured.matcher.ResponseAwareMatcherComposer.*;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.specification.ResponseSpecification;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import io.restassured.mapper.ObjectMapperType;
import static io.restassured.path.json.JsonPath.*;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import static org.hamcrest.Matchers.*;

Tuesday, July 2, 2019

Running suites in Junit Testing Java


import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(FirstTest.class, SecondTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
//First test class
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FirstTest {
@Test
public void equal() {
assertTrue(true);
System.out.println("First test ===>PASSSED");
}
}
//Second test class
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class SecondTest {
@Test
public void add() {
assertFalse("This is failed by me",true);
System.out.println("Second test ===> PASSSED");
}
}
//you can run this by @RunWith(Suit.class) Annotaotions @Suit.SuitClass like below as well
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
FirstTest.class, SecondTest.class
})
public class JunitTestSuit {
}
view raw TestRunner.java hosted with ❤ by GitHub

Sunday, June 30, 2019

Read text on Image file by using Tess4J Selnium Java


package tesss;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
/*<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.3.1</version>
</dependency>*/
public class Tesss {
public static void main(String[] args) throws TesseractException, InterruptedException {
/*
* File src = new File("C:\\OCR\\tess.png"); Tesseract tesseract = new
* Tesseract(); String text = tesseract.doOCR(src);
* System.out.println(text);
*/
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mutturaj\\muttu11\\muttu11\\Drivers\\chromedriver.exe");
ChromeOptions ops = new ChromeOptions();
ops.addArguments("--disable-notifications");
WebDriver driver = new ChromeDriver(ops);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/nget/train-search");
driver.findElement(By.id("loginText")).click();
Thread.sleep(5000);
File file = driver.findElement(By.id("captchaImg")).getScreenshotAs(OutputType.FILE);
// C:\\OCR\\tess.png"
String str = new Tesseract().doOCR(file);
String data="C:\\Users\\diya-mutturajh\\test\\tessdata";
//Set path for yout tessdata folder
tesseract.setDatapath(data);
System.out.println(str);
str = str.split("below")[1];
System.out.println(str);
driver.quit();
}
}
view raw Tesss.java hosted with ❤ by GitHub

Saturday, June 29, 2019

Reading texts on the image by using Apache Tess4j


import java.io.File;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
/*<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.3.1</version>
</dependency>*/
public class Tesss {
public static void main(String[] args) throws TesseractException {
/*File src = new File("C:\\OCR\\tess.png");
Tesseract tesseract = new Tesseract();
String text = tesseract.doOCR(src);
System.out.println(text);*/
System.out.println(new Tesseract().doOCR(new File("C:\\OCR\\tess.png")));
}
}
view raw Tesss.java hosted with ❤ by GitHub

Wednesday, May 29, 2019

Fluent wait in Selenium


import java.time.Duration;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
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.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import com.google.common.base.Function;
public class FluentWaitExample {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mitturaj.h\\Desktop\\chromedriver_win321\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get("https://hulagabal.blogspot.com/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(4000))
.pollingEvery(Duration.ofMillis(300)).ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.xpath("//a[text()='Finding element ByChained using chained class']"));
}
});
System.out.println(foo.getText());
foo.click();
}
}

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

Alternative to Assert in TestNG Java

package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class GoogleTest {
@Test
public void launchPage() throws Exception {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mitturaj.h\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
// by using try and catch
try {
Assert.assertEquals(driver.getTitle(), "Goo");
} catch (Throwable t) {
System.out.println("Failed " + t);
}
System.out.println("##THIS LINE WILL BE EXECUTED##");
}
}
package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class GoogleTest {
@Test
public void launchPage() throws Exception {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Mitturaj.h\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
// by using Soft Assert
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(driver.getTitle(), "Goo");
System.out.println("##THIS LINE WILL BE EXECUTED##");
// use assertAll at the end of all the statement
softAssert.assertAll();
}
}

Wednesday, May 8, 2019

Data-provider via Annotation Transformer TestNG Java


package selenium;
import java.io.File;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.testng.annotations.DataProvider;
public class MyDataProvider {
static String[][] data;
@DataProvider(name = "mydata")
public static Object[][] supplyData() throws Exception {
return getdata();
}
private static String[][] getdata() throws Exception {
Workbook workbook = WorkbookFactory.create(new File("C:\\Users\\Mitturaj.h\\Desktop\\data - Copy.xls"));
Sheet sheet = workbook.getSheetAt(0);
int rows = sheet.getLastRowNum() + 1;
System.out.println(rows);
int cols = sheet.getRow(0).getLastCellNum();
System.out.println(cols);
data = new String[rows][cols];
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
DataFormatter formatter = new DataFormatter();
String user = formatter.formatCellValue(sheet.getRow(x).getCell(y));
System.out.println(user);
data[x][y] = user;
}
}
return data;
}
public static void main(String[] args) throws Exception {
getdata();
}
}
package selenium;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
public class MyListener implements IAnnotationTransformer {
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
if (testMethod.getName().equals("method3")) {
annotation.setPriority(0);
annotation.setDataProviderClass(selenium.MyDataProvider.class);
annotation.setDataProvider("mydata");
}
}
}
view raw MyListener.java hosted with ❤ by GitHub
package selenium;
import org.testng.annotations.Test;
public class SeleniumExample {
@Test(priority = 2)
public void method1() {
System.out.println("Method1");
}
@Test(priority = 1)
public void method2() {
System.out.println("Method2");
}
@Test(priority = 0)
public void method3(String fname, String lname, String number) {
System.out.println("Method3");
System.out.println(fname + " " + lname + " " + number);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<listeners>
<listener class-name="selenium.MyListener"/>
</listeners>
<test name="Test">
<classes>
<class name="selenium.SeleniumExample"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

IAnnotationTransformer in TestNG Java

package selenium;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
public class MyListener implements IAnnotationTransformer {
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
if(testMethod.getName().equals("method3")){
annotation.setPriority(2);
annotation.setEnabled(false);
}
}
}
view raw MyListener.java hosted with ❤ by GitHub
package selenium;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(selenium.MyListener.class)
public class SeleniumExample {
@Test(testName="Method1", priority=2)
public void method1(){
System.out.println("Method1");
}
@Test(priority=1)
public void method2(){
System.out.println("Method2");
}
@Test(testName="Method3", priority=0)
public void method3(){
System.out.println("Method3");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<listeners>
<listener class-name="selenium.AnnotationTransformer" />
</listeners>
<test name="Test">
<classes>
<class name="selenium.SeleniumExample" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

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

 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

 <?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


 <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!

Friday, April 26, 2019

Screen recorder by using Monte recorder

 package video;  
 import static org.monte.media.FormatKeys.EncodingKey;  
 import static org.monte.media.FormatKeys.FrameRateKey;  
 import static org.monte.media.FormatKeys.KeyFrameIntervalKey;  
 import static org.monte.media.FormatKeys.MIME_QUICKTIME;  
 import static org.monte.media.FormatKeys.MediaTypeKey;  
 import static org.monte.media.FormatKeys.MimeTypeKey;  
 import static org.monte.media.VideoFormatKeys.CompressorNameKey;  
 import static org.monte.media.VideoFormatKeys.DepthKey;  
 import static org.monte.media.VideoFormatKeys.ENCODING_QUICKTIME_JPEG;  
 import static org.monte.media.VideoFormatKeys.QualityKey;  
 import java.awt.Dimension;  
 import java.awt.GraphicsConfiguration;  
 import java.awt.GraphicsEnvironment;  
 import java.awt.Rectangle;  
 import java.awt.Toolkit;  
 import java.io.File;  
 import org.monte.media.Format;  
 import org.monte.media.FormatKeys.MediaType;  
 import org.monte.media.math.Rational;  
 import org.monte.screenrecorder.ScreenRecorder;  
 public class VedioOne {  
      private static ScreenRecorder screenRecorder;  
      public static final String USER_DIR = "user.dir";  
      public static final String DOWNLOADED_FILES_FOLDER = "videos";  
      public static void start() throws Exception{  
           File file = new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER);  
           Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
           int width = screenSize.width;  
           int height = screenSize.height;  
           Rectangle captureSize = new Rectangle(0, 0, width, height);  
           GraphicsConfiguration gc = GraphicsEnvironment  
                     .getLocalGraphicsEnvironment().getDefaultScreenDevice()  
                     .getDefaultConfiguration();  
                     // Create a instance of ScreenRecorder with the required configurations  
                     screenRecorder = new ScreenRecorder(gc,captureSize, new Format(MediaTypeKey,MediaType.FILE, MimeTypeKey, MIME_QUICKTIME),  
                     new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey,ENCODING_QUICKTIME_JPEG, CompressorNameKey,  
                     ENCODING_QUICKTIME_JPEG, DepthKey, (int) 24,FrameRateKey, Rational.valueOf(15), QualityKey, 1.0f,  
                     KeyFrameIntervalKey, (int) (15 * 60)),  
                     new Format(MediaTypeKey,MediaType.VIDEO, EncodingKey, "black", FrameRateKey,Rational.valueOf(30)),  
                     null,file);  
                     // Call the start method of ScreenRecorder to begin recording  
                     screenRecorder.start();  
      }  
      public static void stop() throws Exception{  
           screenRecorder.stop();  
      }  
 }  
 <dependency>  
   <groupId>com.github.stephenc.monte</groupId>  
   <artifactId>monte-screen-recorder</artifactId>  
   <version>0.7.7.0</version>  
 </dependency>  
 package seleniumWebdriver;  
 import java.awt.Robot;  
 import java.awt.event.KeyEvent;  
 import org.testng.annotations.Test;  
 import takescreenshot.BaseClass;  
 import video.VedioOne;  
 public class RobotExample extends BaseClass {  
      @Test  
      public void open() throws Exception{  
           //Start recorder  
           VedioOne.start();  
           driver.navigate().to("https://www.youtube.com/");  
           Robot robot=new Robot();  
           robot.keyPress(KeyEvent.VK_TAB);  
           Thread.sleep(2000);  
           robot.keyPress(KeyEvent.VK_TAB);  
           Thread.sleep(2000);  
           robot.keyPress(KeyEvent.VK_TAB);  
           Thread.sleep(2000);  
           robot.keyPress(KeyEvent.VK_TAB);  
           Thread.sleep(2000);  
           robot.keyPress(KeyEvent.VK_ENTER);  
           Thread.sleep(2000);  
           driver.close();  
           //Stop recorder  
           VedioOne.stop();  
      }  
 }  

Wednesday, April 24, 2019

Retrieve data from Excel file by using Apache POI

 package fileio;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
 import org.apache.poi.ss.usermodel.Sheet;  
 import org.apache.poi.ss.usermodel.Workbook;  
 import org.apache.poi.ss.usermodel.WorkbookFactory;  
 public class POI123 {  
      //This method id used to get data from the xls OR xlsx file by using browser factory class  
      public static String getdata1() throws Exception {  
           Workbook workbook = WorkbookFactory.create(new File("C:\\Users\\Mitturaj.h\\Desktop\\data.xls"));  
           Sheet sheet = workbook.getSheetAt(0);  
           int rows = sheet.getLastRowNum();  
           System.out.println(rows);  
           String value = sheet.getRow(0).getCell(0).getStringCellValue();  
           System.out.println(value);  
           return value;  
      }  
      // this is method is used to get data from the .xls file by using HSSF class  
      public static String getdata2() throws Exception {  
           HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("C:\\Users\\Mitturaj.h\\Desktop\\data.xls"));  
           Sheet sheet = workbook.getSheetAt(0);  
           int rows = sheet.getLastRowNum();  
           String data = sheet.getRow(0).getCell(0).getStringCellValue();  
           System.out.println(rows);  
           System.out.println(data);  
           return data;  
      }  
      public static void getdata3() throws Exception{  
           HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream("C:\\Users\\Mitturaj.h\\Desktop\\data.xlsx"));  
           Sheet sheet=workbook.getSheetAt(0);  
           String value=sheet.getRow(0).getCell(0).getStringCellValue();  
           System.out.println(value);  
      }  
      public static void main(String[] args) throws Exception {  
           getdata2();  
           getdata1();  
           getdata3();  
      }  
 }  

Tuesday, April 16, 2019

log4j2

 <?xml version="1.0" encoding="UTF-8"?>  
 <Configuration status="warn">  
      <Properties>  
           <Property name="basePath">C:\\Users\\Mitturaj.h\\Selenium-Learning\\Selenium-Learning\\test-output  
           </Property>  
      </Properties>  
      <Appenders>  
           <RollingFile name="fileLogger" fileName="${basePath}/app-info.log"  
                filePattern="${basePath}/app-info-%d{yyyy-MM-dd}.log">  
                <PatternLayout>  
                     <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
                     </pattern>  
                </PatternLayout>  
                <Policies>  
                     <TimeBasedTriggeringPolicy interval="1"  
                          modulate="true" />  
                </Policies>  
           </RollingFile>  
           <RollingFile name="Logger" fileName="${basePath}/app-log.log"  
                filePattern="${basePath}/app-info-%d{yyyy-MM-dd}.log">  
                <PatternLayout>  
                     <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
                     </pattern>  
                </PatternLayout>  
                <Policies>  
                     <TimeBasedTriggeringPolicy interval="1"  
                          modulate="true" />  
                </Policies>  
           </RollingFile>  
           <Console name="console" target="SYSTEM_OUT">  
                <PatternLayout  
                     pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />  
           </Console>  
      </Appenders>  
      <Loggers>  
           <!-- file-logger is ref to rolling file name: fileLogger -->  
           <Logger name="apachepoi" level="debug" additivity="true">  
                <appender-ref ref="fileLogger" level="debug" />  
           </Logger>  
           <!-- logger ref is here reference to Rolling File name:Logger -->  
           <Logger name="log4j2" level="debug" additivity="true">  
                <appender-ref ref="Logger" level="debug" />  
           </Logger>  
           <Root level="debug" additivity="false">  
                <appender-ref ref="console" />  
           </Root>  
      </Loggers>  
 </Configuration>  


 package log4j2;  
 import org.apache.logging.log4j.LogManager;  
 public class LogIt {  
      private static final org.apache.logging.log4j.Logger LOGGER=LogManager.getLogger(LogIt.class.getName());  
      public static void main(String[] args) {  
           LOGGER.info("Loggin here");  
      }  
 }  


Get all keys and values from the properties file

 package muttutest;  
 import java.io.FileInputStream;  
 import java.io.InputStream;  
 import java.util.Properties;  
 import java.util.Set;  
 public class Prop {  
      public static Properties loadPropertiesFile() throws Exception {  
           Properties prop = new Properties();  
           InputStream in = new FileInputStream(  
                     "C:\\Users\\Mutturaj\\workspace\\maven-learn\\src\\test\\java\\muttutest\\muttu.properties");  
           prop.load(in);  
           in.close();  
           return prop;  
      }  
      public static void main(String[] args) {  
           try {  
                Properties properties = loadPropertiesFile();  
                Set<Object> set = properties.keySet();  
                for (Object o : set) {  
                     String key = (String) o;  
                     System.out.println("key: " + key + " value: " + properties.getProperty(key));  
                }  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
 }  

Monday, April 15, 2019

Get data from properties file by File Input Stream and File Reader

 package muttutest;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileReader;  
 import java.util.Properties;  
 public class SysProps {  
      static Properties properties, properties2;  
      public static void main(String[] args) throws Exception {  
           File file = new File(  
                     "C:\\Users\\Mutturaj\\workspace\\maven-learn\\src\\test\\java\\muttutest\\muttu.properties");  
           //File Input Stream  
           FileInputStream inStream = new FileInputStream(file);  
           properties.load(inStream);  
           System.out.println(properties.getProperty("name"));  
           //File reader  
           FileReader fileReader = new FileReader(  
                     "C:\\Users\\Mutturaj\\workspace\\maven-learn\\src\\test\\java\\muttutest\\muttu.properties");  
           properties2=new Properties();  
           properties2.load(fileReader);  
           System.out.println(properties2.getProperty("name"));  
      }  
 }  

Apache POI Workbook Factory in Java

 package test;  
 import java.io.FileInputStream;  
 import org.apache.poi.ss.usermodel.Sheet;  
 import org.apache.poi.ss.usermodel.Workbook;  
 import org.apache.poi.ss.usermodel.WorkbookFactory;  
 import org.testng.annotations.DataProvider;  
 import org.testng.annotations.Test;  
 public class DataExcel {  
      private static String[][] users;  
      public static String[][] getData() throws Exception {  
           Workbook workbook = WorkbookFactory.create(new FileInputStream("C:\\Users\\Mitturaj.h\\Desktop\\data.xlsx"));  
           Sheet sheet = workbook.getSheet("Sheet1");  
           int noOfRows = sheet.getLastRowNum() + 1;  
           System.out.println(noOfRows);  
           users = new String[noOfRows][2];  
           for (int i = 0; i < noOfRows; i++) {  
                for (int j = 0; j < 2; j++) {  
                     String user = sheet.getRow(i).getCell(j).getStringCellValue();  
                     users[i][j] = user;  
                }  
           }  
           return users;  
      }  
      @DataProvider(name = "users")  
      public static Object[][] getUsers() throws Exception {  
           return getData();  
      }  
      @Test(dataProvider = "users")  
      public void login(String username, String pass) {  
           System.out.println(username + " " + pass);  
      }  
 }  
           <dependency>  
                <groupId>org.apache.poi</groupId>  
                <artifactId>poi-ooxml</artifactId>  
                <version>3.17</version>  
           </dependency>  
           <dependency>  
                <groupId>org.apache.poi</groupId>  
                <artifactId>poi</artifactId>  
                <version>3.17</version>  
           </dependency>  
           <dependency>  
                <groupId>org.apache.poi</groupId>  
                <artifactId>ooxml-schemas</artifactId>  
                <version>1.1</version>  
           </dependency>  
           <dependency>  
                <groupId>org.testng</groupId>  
                <artifactId>testng</artifactId>  
                <version>6.8</version>  
                <scope>test</scope>  
           </dependency>  

Thursday, April 11, 2019

API automation using Rest Assured and TestNG


RestAPITests.java


 package resrassure;  
 import org.json.simple.JSONObject;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 import io.restassured.RestAssured;  
 import io.restassured.http.Method;  
 import io.restassured.response.Response;  
 import io.restassured.specification.RequestSpecification;  
 public class RestAPITests {  
      @Test  
      public void checkSometing() {  
           // https://restapi.demoqa.com/utilities/weather/city/hyderabad  
           RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city";  
           RequestSpecification request = RestAssured.given();  
           Response response = request.request(Method.GET, "/Hyderabad");  
           int statusCode = response.statusCode();  
           System.out.println(statusCode);  
           String statusLine = response.getStatusLine();  
           System.out.println(statusLine);  
           String responceBody = response.getBody().asString();  
           System.out.println(responceBody);  
           Assert.assertEquals(statusCode, 200);  
           Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");  
      }  
      @Test  
      public void register() {  
           // https://restapi.demoqa.com/customer/register  
           RestAssured.baseURI = "https://restapi.demoqa.com/customer";  
           RequestSpecification request = RestAssured.given();  
           // Add the parameters to the Json object  
           //Its like has map 'Key' 'Value' pair  
           JSONObject params = new JSONObject();  
           params.put("FirstName", "muttu");  
           params.put("LastName", "muttu");  
           params.put("UserName", "muttu3");  
           params.put("Password", "muttu123");  
           params.put("Email", "muttu3@gmail.com");  
           // Add header stating the request body ia a JSON  
           request.headers("Content-Type", "application/json");  
           // Add Json params to the body of the request  
           request.body(params.toJSONString());  
           // Post the request and check the response  
           Response response = request.post("/register");  
           System.out.println(response.body().asString());  
           // Get the status code from the response  
           int statusCode = response.getStatusCode();  
           System.out.println(statusCode);  
           Assert.assertEquals(statusCode, 201);  
           // Get the success code form the response  
           String successCode = response.jsonPath().get("SuccessCode");  
           Assert.assertEquals(successCode, "OPERATION_SUCCESS");  
           // Get the success Message from the response  
           String successMessage = response.jsonPath().get("Message");  
           Assert.assertEquals(successMessage, "Operation completed successfully");  
      }  
 }  

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.hulagabal</groupId>  
      <artifactId>testex</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>io.rest-assured</groupId>  
                <artifactId>rest-assured</artifactId>  
                <version>3.3.0</version>  
                <scope>test</scope>  
           </dependency>  
           <dependency>  
                <groupId>com.googlecode.json-simple</groupId>  
                <artifactId>json-simple</artifactId>  
                <version>1.1.1</version>  
           </dependency>  
      </dependencies>  
 </project>  

TestNG.xml

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite" parallel="true">  
  <test name="Test">  
   <classes>  
    <class name="resrassure.RestAPITests"/>  
   </classes>  
  </test> <!-- Test -->  
 </suite> <!-- Suite -->  

Wednesday, April 10, 2019

Creating TestNG in java program

 package sample;  
 import org.testng.annotations.Test;  
 public class Sample {  
      @Test  
      public void sample1() {  
           System.out.println("************Sample***sample1***************");  
           System.out.println("***********Sample****sample1***************");  
      }  
      @Test  
      public void sample2() {  
           System.out.println("***********Sample****sample2***************");  
           System.out.println("***********Sample****sample2***************");  
      }  
 }  


 package sample;  
 import org.testng.annotations.Test;  
 public class Sample2 {  
      @Test  
      public void sample1() {  
           System.out.println("************Sample2***sample1***************");  
           System.out.println("***********Sample2****sample1***************");  
      }  
      @Test  
      public void sample2() {  
           System.out.println("************Sample2***sample2***************");  
           System.out.println("************Sample2***sample2***************");  
      }  
 }  





 package sample;  
 import org.testng.ITestContext;  
 import org.testng.ITestListener;  
 import org.testng.ITestResult;  
 public class MyListener implements ITestListener {  
      public void onFinish(ITestContext arg0) {  
           System.out.println("finnished");  
      }  
      public void onStart(ITestContext arg0) {  
           System.out.println("Just started");  
      }  
      public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {  
      }  
      public void onTestFailure(ITestResult arg0) {  
      }  
      public void onTestSkipped(ITestResult arg0) {  
      }  
      public void onTestStart(ITestResult arg0) {  
           System.out.println("Test started");  
      }  
      public void onTestSuccess(ITestResult arg0) {  
           System.out.println("Test suceess");  
      }  
 }  




 package sample;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.testng.TestNG;  
 import org.testng.xml.XmlClass;  
 import org.testng.xml.XmlSuite;  
 import org.testng.xml.XmlTest;  
 public class TestngExample {  
      public static void main(String[] args) {  
           XmlSuite suite = new XmlSuite();  
           suite.setName("MySuite");  
           suite.setParallel("false");  
           suite.setVerbose(1);  
           suite.addListener("sample.MyListener"); // add listener class  
           XmlTest test1 = new XmlTest(suite);  
           test1.setName("Test1");  
           test1.setPreserveOrder("true");  
           XmlTest test2 = new XmlTest(suite);  
           test2.setName("Test2");  
           test2.setPreserveOrder("true");  
           XmlClass class1 = new XmlClass(Sample.class);  
           XmlClass class2 = new XmlClass(Sample2.class);  
           // Arraylist to add classes  
           List<XmlClass> classes = new ArrayList<XmlClass>();  
           classes.add(class1);  
           classes.add(class2);  
           test1.setClasses(classes);  
           test2.setClasses(classes);  
           TestNG testng = new TestNG();  
           // arraylist to add uites  
           List<XmlSuite> suites = new ArrayList<XmlSuite>();  
           suites.add(suite);  
           testng.setXmlSuites(suites);  
           testng.run();  
      }  
 }  


Tuesday, April 2, 2019

Log4j2 for selenium webdriver

put it in //src/test/resources/log4j2.properties in the Maven project



 name=PropertiesConfig  
 property.filename = logs  
 appenders = console, file  
 appender.console.type = Console  
 appender.console.name = STDOUT  
 appender.console.layout.type = PatternLayout  
 appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
 appender.file.type = File  
 appender.file.name = LOGFILE  
 appender.file.fileName=${filename}/Mylogs.log  
 appender.file.layout.type=PatternLayout  
 appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
 loggers=file  
 logger.file.name=your package name here  
 logger.file.level = debug  
 logger.file.appenderRefs = file  
 logger.file.appenderRef.file.ref = LOGFILE  
 logger.file.appender  
 rootLogger.level = debug  
 rootLogger.appenderRefs = stdout  
 rootLogger.appenderRef.stdout.ref = STDOUT  

To access in any class

Create variable in the class level :

 private Logger logger = LogManager.getLogger(yourclass.class);  

use it wherever you want like this:

 logger.info("log message");  

Sunday, March 31, 2019

Dr Jordan B Peterson

Are you alive? That means you're all in, so you might as well play your most magnificent game. Ask yourself today: how much good can I do, or what's the best thing I can do? This is one of the ways to justify existence.
Orient yourself to the highest possible good that you can conceive and commit to it. You're way more powerful than you think.

Wednesday, March 27, 2019

Log4j2

log4j2.properties


 name=PropertiesConfig  
 property.filename = logs  
 appenders = console, file  
 appender.console.type = Console  
 appender.console.name = STDOUT  
 appender.console.layout.type = PatternLayout  
 appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
 appender.file.type = File  
 appender.file.name = LOGFILE  
 appender.file.fileName=${filename}/myLogs.log  
 appender.file.layout.type=PatternLayout  
 appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
 loggers=file  
 logger.file.name=kavoor  
 logger.file.level = debug  
 logger.file.appenderRefs = file  
 logger.file.appenderRef.file.ref = LOGFILE  
 rootLogger.level = debug  
 rootLogger.appenderRefs = stdout  
 rootLogger.appenderRef.stdout.ref = STDOUT  


SampleTest.java


 package kavoor;  
 import org.apache.logging.log4j.LogManager;  
 import org.apache.logging.log4j.Logger;  
 public class LoggerSample {  
      private static Logger logger = LogManager.getLogger(LoggerSample.class);  
      public static void main(String[] args) {  
           logger.info("Info");  
           logger.warn("Warn");  
           logger.debug("Debug");  
           logger.error("Error");  
           logger.fatal("Fatal");  
      }  
 }  


Mylogs.log


 [INFO ] 2019-03-27 15:55:06.748 [main] LoggerSample - Info  
 [WARN ] 2019-03-27 15:55:06.751 [main] LoggerSample - Warn  
 [DEBUG] 2019-03-27 15:55:06.751 [main] LoggerSample - Debug  
 [ERROR] 2019-03-27 15:55:06.751 [main] LoggerSample - Error  
 [FATAL] 2019-03-27 15:55:06.751 [main] LoggerSample - Fatal  




Tuesday, March 26, 2019

8 Ways to Become a Better Coder


It’s time to get serious about improving your programming skills. Let’s do it!
That’s an easy career improvement goal to give oneself, but “become a kick-ass programmer” is not a simple goal. For one thing, saying, “I want to get better” assumes that you recognize what “better” looks like. Plus, too many people aim for improvement without any sense of how to get there.
So let me share eight actionable guidelines that can act as a flowchart to improving your programming skills. These tidbits of wisdom are gathered from 35 years in the computer industry, many of which were spent as a lowly grasshopper at the feet of some of the people who defined and documented it.
1. Remind yourself how much you have to learn
The first step in learning something is recognizing that you don’t know it. That sounds obvious, but experienced programmers remember how long it took to overcome this personal assumption. Too many computer science students graduate with an arrogant “I know best” bravado, a robust certainty that they know everything and the intense need to prove it to every new work colleague. In other words: Your “I know what I’m doing!” attitude can get in the way of learning anything new.

2. Stop trying to prove yourself right

To become great—not just good—you have to learn from experience. But be careful, experience can teach us to repeat poor behavior and to create bad habits. We’ve all encountered programmers with eight years of experience … the same year of experience, repeated eight times. To avoid that syndrome, look at everything you do and ask yourself, “How can I make this better?”
Novice software developers (and too many experienced ones) look at their code to admire its wonderfulness. They write tests to prove that their code works instead of trying to make it fail. Truly great programmers actively look for where they’re wrong—because they know that eventually users will find the defects they missed.

3. “The code works” isn’t where you stop; it’s where you start

Yes, your first step is always to write quality software that fulfills the spec. Average programmers quit at that point and move on to the next thing.
But to stop once it’s “done” is like taking a snapshot and expecting it to be a work of art. Great programmers know that the first iteration is just the first iteration. It works— congratulations!—but you aren’t done. Now, make it better.
Part of that process is defining what “better” means. Is it valuable to make it faster? Easier to document? More reusable? More reliable? The answer varies with each application, but the process doesn’t.

4. Write it three times

Good programmers write software that works. Great ones write software that works exceedingly well. That rarely happens on the first try. The best software usually is written three times:
  1. First, you write the software to prove to yourself (or a client) that the solution is possible. Others may not recognize that this is just a proof-of-concept, but you do.
  2. The second time, you make it work.
  3. The third time, you make it work right.
This level of work may not be obvious when you look at the work of the best developers. Everything they do seems so brilliant, but what you don’t see is that even rock-star developers probably threw out the first and second versions before showing their software to anyone else. Throwing away code and starting over can be a powerful way to include “make it better” into your personal workflow.
If nothing else, “Write it three times” teaches you how many ways there are to approach a problem. And it prevents you from getting stuck in a rut.

5. Read code. Read lots of code

You probably expected me to lead with this advice, and indeed it’s both the most common and the most valuable suggestion for improving programming skills. What is less evident are the reasons that reading others’ code is so important.
When you read others’ code, you see how someone else solved a programming problem. But don’t treat it as literature; think of it as a lesson and a challenge. To get better, ask yourself:
  • How would I have written that block of code? What would you do differently, now that you’ve seen another solution?
  • What did I learn? How can I apply that technique to code I wrote in the past? (“I’d never have thought to use recursive descent there…”).
  • How would I improve this code? And if it’s an open source project where you are confident you have a better solution, do it!
  • Write code in the author’s style. Practicing this helps you get into the head of the person who wrote the software, which can improve your empathy.
Don’t just idly think about these steps. Write out your answers, whether in a personal journal, a blog, in a code review process, or a community forum with other developers. Just as explaining a problem to a friend can help you sort out the solution, writing down and sharing your analysis can help you understand why you react to another person’s code in a given way. It’s all part of that introspection I mentioned earlier, helping you to dispassionately judge your own strengths and weaknesses.
Warning: It’s easy to read a lot of code without becoming a great programmer, just as a wannabe writer can read great literature without improving her own prose. Plenty of developers look at open source or other software to “find an answer” and, most likely, to copy and paste code that appears to solve a similar problem. Doing that can actually make you a worse programmer, since you are blindly accepting others’ wisdom without examining it. (Plus, it may be buggier than a summer picnic, but because you didn’t take the time to understand it, you’ll never recognize that you just imported a bug-factory.)
6. Write code, and not just as assignments
Working on personal programming projects has many advantages. For one, it gives you a way to learn tools and technologies that aren’t available at your current job, but which make you more marketable for the next one. Whether you contribute to an open source project or take on pro-bono work for a local community organization, you’ll gain tech skills and self-confidence. (Plus, your personal projects demonstrate to would-be employers that you’re a self-starter who never stops learning.)
Another advantage of writing code for fun is that it forces you to figure things out on your own. You can’t leave the hard stuff to someone else, so it keeps you from asking for help too soon.
Pro tip: Don’t choose only personal projects where you never fail. You need to fail! But you do probably don’t want to fail at work or when you have a deadline.
7. Work one-on-one with other developers any way you can
It helps to listen to other people. That might mean pair programming, or going to a hackathon, or joining a programming user group (such as the Vermont Coders Connection). When you contribute to an open source project, pay attention to the feedback you get from users and from other developers. What commonalities do you see in their criticism?
You might be lucky enough to find a personal mentor whom you can trust to guide you in everything from coding techniques to career decisions. Don’t waste these opportunities.

8. Learn techniques, not tools

Programming languages, tools, and methodologies come and go. That’s why it pays to get as much experience as you can with as many languages and frameworks as possible. Focus on the programming fundamentals, because the basics never change; pay more attention to architecture than to programming. If you feel certain that there’s only one right way to do something, it’s probably time for a reality check. Dogma can hamper your ability to learn new things, and make you slow to adapt to change.
I could keep going, but a key tenet of self-improvement is knowing when to stop.

Saturday, March 23, 2019

ITestListener in TestNG Selenium




Test file

 package learning;  
 import org.testng.Assert;  
 import org.testng.annotations.Listeners;  
 import org.testng.annotations.Test;  
 @Listeners(MyListeners.class)  
 public class ListenerExample {  
      @Test  
      public void testToFail() {  
           Assert.assertTrue(false);  
      }  
      public void testToPass(){  
           Assert.assertTrue(true);  
      }  
 }  


Listener class

 package learning;  
 import org.testng.ITestContext;  
 import org.testng.ITestListener;  
 import org.testng.ITestResult;  
 import org.testng.SkipException;  
 public class MyListeners implements ITestListener {  
      @Override  
      public void onTestStart(ITestResult result) {  
           System.out.println("Test started " + result);  
      }  
      @Override  
      public void onTestSuccess(ITestResult result) {  
           System.out.println("This test passed " + result);  
      }  
      @Override  
      public void onTestFailure(ITestResult result) {  
           System.out.println("This test failed " + result);  
      }  
      @Override  
      public void onTestSkipped(ITestResult result) {  
           System.out.println("Test is Skipped " + result);  
           throw new SkipException("Skipping this exception");  
      }  
      @Override  
      public void onTestFailedButWithinSuccessPercentage(ITestResult result) {  
      }  
      @Override  
      public void onStart(ITestContext context) {  
           System.out.println("Test started");  
      }  
      @Override  
      public void onFinish(ITestContext context) {  
           System.out.println("Test finnished");  
      }  
 }  


TestNG.xml

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite">  
      <listeners>  
           <listener class-name="learning.MyListeners" />  
      </listeners>  
      <test name="Test">  
           <classes>  
                <class name="learning.HilightExample" />  
           </classes>  
      </test> <!-- Test -->  
 </suite> <!-- Suite -->  

Friday, March 22, 2019

Highlight elements in Selenium Webdriver



 package learning;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 public class Hightlight {  
      public static void hilightElement(WebElement element, WebDriver driver) {  
           for (int i = 0; i < 2; i++) {  
                JavascriptExecutor js = (JavascriptExecutor) driver;  
                js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');",  
                          element);  
           }  
      }  
 }  


 package learning;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.testng.annotations.Test;  
 public class HilightExample {  
      @Test  
      public void showIt() {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.get("https://www.flipkart.com/");  
           WebElement element = driver.findElement(By.className("_2zrpKA"));  
           Hightlight.hilightElement(element, driver);  
           element.sendKeys("hulagabal@gmail.com");  
      }  
 }  

Tuesday, March 12, 2019

Data provider in TestNG

 package muttu.test;  
 import org.testng.annotations.DataProvider;  
 import org.testng.annotations.Test;  
 public class DataProviderDemo {  
      @DataProvider(name = "LoginDeatls")  
      public Object[][] getUserDetails() {  
           return new Object[][] { { "uName1", "pwd1" }, { "uName2", "pwd2" } };  
      }  
      @Test(dataProvider = "LoginDeatls")  
      public void Login(String name, String password) {  
           System.out.println(name);  
           System.out.println(password);  
      }  
 }