MainMenu

Home Core Java Overview Maven Tutorials

Sunday, 1 July 2018

How to perform upload operation in selenium

How to upload the file using selenium

Click Here to navigate on practice page



Hello Friends, In this tutorial we will learn how to perform upload operation in selenium.
We can perform the upload operation in selenium by two ways :
1). First by SendKeys() method.
2). Second by using the robot class.
First Method :
Precondition : Element should be input and type should be "file", as shown below :



Now we just need to locate the element and just use the method sendKeys() and in sendKeys() method we will pass the path of that file.
Syntax :-
driver.findElement(By.xpath("path of element")).sendKeys("path on file");

Here is sample code :-

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Uploadfile
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
/*FirefoxOptions foptions = new FirefoxOptions();
foptions.setCapability("marionette", false);
driver = new FirefoxDriver(foptions);*/
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
Thread.sleep(3000);
}
@Test
public void h()
{
//Remember element should be input and type should be "file"
driver.findElement(By.xpath(".//*[@id='post-body-2064404811754288590']/form[1]/input[1]")).sendKeys("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
}
}





Second Method : By using Robot Class:-
What is Robot class ?
"Basically robot class will simulate the Keyboard and mouse actions."
Steps :-
1). First Copy the file path.
2).Paste the file path in popup window
3).Press Enter button.

by robot class we can perform CTRL + C operation by below methods as :-
StringSelection ss = new StringSelection("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

by robot class we can perform CTRL + V operation as below :-
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);



by robot class we can press enter key as below :-
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Here is sample code :-

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Uploadfile
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
/*FirefoxOptions foptions = new FirefoxOptions();
foptions.setCapability("marionette", false);
driver = new FirefoxDriver(foptions);*/
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
Thread.sleep(3000);
}
@Test
public void h() throws AWTException
{
driver.findElement(By.xpath(".//*[@id='post-body-2064404811754288590']/form[1]/input[1]")).click();
Robot robot = new Robot();
robot.setAutoDelay(2000);
StringSelection ss = new StringSelection("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
robot.setAutoDelay(2000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}



TAGS :-

How to perform control + c operation in selenium

How to upload a file in selenium

Example to upload a file in selenium

upload a file in selenium using robot class

upload a file in selenium using sendkeys methods

Thursday, 28 June 2018

Find Duplicate Element in Array, Find count of duplicate element in array, remove duplicate element from array


Hello Friends,

In this article , we will learn , Three below things :-
1). How to Find Duplicate Element in array
2). How to find count of duplicate element in array.
3). How to remove duplicate element from array.
Note : It is very important tutorial for interview purpose.

Video :


It can be achieved by simple below algorithm :-
First create a collection.
now compare each element, within this collection
If collection have that element, than ignore else add this element to collection.

Below is Sample code :-

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class Interviewtest
{
//find the duplicate elements in the array
int count;
public static void main(String args[])
{
int arr[] = {4, 2, 2, 4, 55, 6, 99, 55};
AtomicInteger count = new AtomicInteger(1);
Set newarray = new HashSet();
for(int i =0; i<arr.length; i++)
{
if(newarray.contains(arr[i]))
{
int x = count.getAndIncrement();
//System.out.println("Element"+ " " + arr[i] + " " + x);
}
else
{
newarray.add(arr[i]);
}
for(int j =i+1; j<arr.length; j++)
{
if(arr[i]==arr[j])
{
System.out.println("Duplicate element is:->" +" "+arr[i]);
}
}
}
System.out.println(newarray);
g();
h();
}
public static void g()
{
String arr[] = new String[]{"chandan", "adhiraj", "Tina", "Cathy", "chandan", "adhiraj"};
Set duplicate = new HashSet<>();
Set nonduplicate = new HashSet<>();
for(String srting : arr)
{
/*if(!nonduplicate.contains(srting))
{
nonduplicate.add(srting);
}
else
{
duplicate.add(srting);
}*/
if(nonduplicate.contains(srting))
{
duplicate.add(srting);
}
else
{
nonduplicate.add(srting);
}
}
System.out.println(duplicate);
System.out.println(nonduplicate);
}
public static void h()
{
int arr[] = {4, 2, 2, 4, 55, 6, 99, 55};
for(int i =0; i<arr.length; i++)
{
int t = 1;
for(int j =i+1; j<arr.length; j++)
{
if(arr[i]==arr[j])
{
t = t+1;
}
}
System.out.println("Element" + " " + arr[i] + " " + "occurs" + " " + t);
}
}
}

Monday, 14 May 2018

How To Perform Right Click Action (Context Click) In Selenium


Hello Friends,

In this article , we will learn , how to perform right click of mouse & select option "Open Link in New Tab" and "Open Link in New Window" using selenium webdriver.

Video :


Open link in new Tab :
So we will take an easy scenario as below :
Launch the browser
Navigate to the URL
right click on any link
select the option "Open Link in New Tab"
switch to new tab & perform some operation
close the new tab & switch back to parent tab.

To achieve this we will write a simple code in TestNG.

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Opennewtab
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h()
{
WebElement seleniumtutorial = driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/center/div[1]/table/tbody/tr[1]/td[4]/a/img"));
Actions action = new Actions(driver);
action.contextClick(seleniumtutorial).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String windowhandler = driver.getWindowHandle();
ArrayList tabs2 = new ArrayList (driver.getWindowHandles());
System.out.println(tabs2.size());
driver.switchTo().window((String) tabs2.get(1));
String link = driver.findElement(By.xpath(".//*[@id='post-body-7737945062927568046']/table[1]/tbody/tr[1]/td[1]/h2/a")).getAttribute("href");
System.out.println(link);
driver.close();
driver.switchTo().window(windowhandler);
System.out.println("i am working fine");
}
}


Open link in new window :
Now again scenarios will be same but opeartion will be performed in new window instead of new tab :

Launch the browser
Navigate to the URL
right click on any link
select the option "Open Link in New window"
switch to new window & perform some operation.
close the new window & switch back to parent window.
To achieve this we will write a simple code in TestNG.

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class OpennewWindow
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h() throws InterruptedException
{
WebElement seleniumtutorial = driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/center/div[1]/table/tbody/tr[1]/td[4]/a/img"));
Actions action = new Actions(driver);
action.contextClick(seleniumtutorial).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String windowhandler = driver.getWindowHandle();
ArrayList tabs2 = new ArrayList (driver.getWindowHandles());
System.out.println(tabs2.size());
driver.switchTo().window(tabs2.get(1));
String link = driver.findElement(By.xpath(".//*[@id='post-body-7737945062927568046']/table[1]/tbody/tr[1]/td[1]/h2/a")).getAttribute("href");
System.out.println(link);
Thread.sleep(3000);
driver.close();
driver.switchTo().window(windowhandler);
System.out.println("i am working fine");
}
}

Sunday, 22 April 2018

Create WebDriver instance for multiple class in different ways


Hello friends,

In this article we will learn how to create WebDriver Instance multiple classes:

So, we will create a WebDriver instance in one class & call it in multiple class
we have achieve this by 2 ways
1).By using extends
2).By using Singleton class

To know about singleton class Click Here

For Video :- Click Here



Method :1By extends Keyword

Step :1Create a class & initialize your driver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MainDriver
{
public static WebDriver driver;
public static void createInstance()
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}


Step :2Create an another class & extend above driver class

public class Testcase1 extends MainDriver
{
public static void url()
{
MainDriver.createInstance();
driver.navigate().to("http://www.way2testing.com");
}
}


Step :3Create an another class & extend above driver class

public class TestCase2 extends MainDriver
{
public static void getTitle()
{
System.out.println(driver.getTitle());
}
}


Step :4Create an another class & extend above driver class

import org.testng.annotations.Test;

public class Excution
{
@Test(priority = 0)
public void getUrl()
{
Testcase1.url();
}
@Test(priority = 1)
public void getTitle()
{
TestCase2.getTitle();
}
}


If you will run this Exeution class , you can see that with one WebDriver Instance(driver), you are able to perform your all task.

Method :2By Singleton Class

Step :1Create a Singleton class & initialize your driver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SingletonDriver
{
public static WebDriver driver = null;
public static void Initiallize()
{
if(driver == null)
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}
public static void close()
{
driver.close();
}
public static void quit()
{
driver.quit();
}
}



Step :2Create a class for your test cases & execute singleclass method

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Testcases
{
@BeforeTest
public void initializeDriver()
{
SingletonDriver.Initiallize();
}
@Test(priority = 0)
public void openurl()
{
SingletonDriver.driver.navigate().to("http://www.way2testing.com");
}
@Test(priority = 1)
public void getTitle()
{
System.out.println(SingletonDriver.driver.getTitle());
}
}



So, by using above methods, you can create a WebDriver Instanse(driver) and can use it in your multiple classes.
Thanks :)





Swap Two variable in Java


Hello friends,

In this article we will discuss about swap variable without using third variable:

For Video :- Click Here



public class Swap
{
int x = 10;
int y = 15;
public static void main(String args[])
{
Swap object = new Swap();
object.g();
}
public void g()
{
x = x+y;
y = x-y;
x = x-y;
System.out.println("After Swap Value of y : " + y);
System.out.println("After Swap Value of x : " + x);
}
}


output :
After Swap Value of y : 10
After Swap Value of x : 15

Code Explanation : Suppose we have two variable x, y and they have value 10, 15 respectively and we want to swap these two variables value.
HOW IT WOULD BE DONE ?
1). First , i will join these two variables value & store it in variable x.
Now the value of x is 25.
2). Now, we will minus the value of y(15) from this x(25).
we will get 10 & will store in variable y
3). Now the value on y is 10 & value of x is 25.
again we will minus this y value from & store it in variable x so value of variable of x will become 15.

Congratulation You have swapped the value of two variable without using third variable. :)





Tags :

Swap two variable without using third variable in Java

how two swap two variable in java without using third variable

Tuesday, 13 March 2018

What is Hashmap in Java? Hashmap vs HashTable


HashMap in java


Hi all, in this demo i will describe about HashMap in java.


Map Interface.
public interface Map
An object that maps key to values. A map cannot contain duplicate keys;each key can map to at most one value.
This interface takes the place of the Disctionary class, which was a totally Abstract Class rather than an interface.

HashMap is important for selenium as well as for interview also.
hashMap is a Map based collection class that is used for storing Key & Value(associated with keys).
1).It is donated as HashMap.
2).Hashmap contains only unique elements.
3).Hashmap may have only one null key and multiple null values
4). Hashmap maintains no order.

Here is the example of HashMap in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class hashmapdemo
{
public static void main(String args[])
{
hashmapdemo obj = new hashmapdemo();
obj.g();
}
public void g()
{
Map< String, Integer > record = new HashMap<>();
record.put("Anjana", 26);
record.put("Silpi", 27);
record.put("Heena", 28);
record.put("Adhiraj", 29);
System.out.println(record.get("Heena"));
Set<String> keys = record.keySet();
for(String i : keys)
{
System.out.println(i + ":" +record.get(i));
}
}
}

Output :

28
Adhiraj:29
Anjana:26
Silpi:27
Heena:28





TreeMap in Java

TreeMap is Red-Black tree based NavigableMap implementation. It is sorted according to the natural ordering of its keys.
TreeMap class implements Map interface similar to HashMap class.
The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys.
TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

Here is the example of TreeMap in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class hashmapdemo
{
public static void main(String args[])
{
hashmapdemo obj = new hashmapdemo();
obj.g();
}
public void g()
{
//Map<String, Integer> record = new HashMap<>();
TreeMap<Integer, String> record = new TreeMap<>();
record.put(26, "Anjana");
record.put(28, "Heena");
record.put( 29, "Adhiraj");
record.put(27, "Silpi");
System.out.println(record.get(28));
for(Integer i : record.keySet())
{
System.out.println(i + ":" +record.get(i));
}
}
}


Output :

Heena
26:Anjana
27:Silpi
28:Heena
29:Adhiraj



HashMap vs TreeMap

Saturday, 3 March 2018

for each loop in java with example


for Each loop in java :
Hi all, in this demo i will describe about for-each loop in java.

This loop is important for selenium as well as for interview also.
So as the name says when we want to perform some operation with each element of the list or collection or array, then we use this loop.
The Syntax of the loop is :
for(data_type variable_name : array|collection)
{
}
it will get more clear when we describe it through an example :

Example of for-each loop in java


public class foreach
{
public static void main(String args[])
{
int arr[] = {10, 20, 30, 44};
for(int x : arr)
{
System.out.println("Your number is :" + x);
}
}
}
---------------------------------------------------------------------------
Now, Suppose you are working in some selenium project, and have create a WebElement list then, you can perform operation with each element using for -each loop

For Each Loop in selenium Example :
import java.util.List;
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.BeforeTest;
import org.testng.annotations.Test;

public class foreach_selenium
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h()
{
List list = driver.findElements(By.cssSelector("#post-body-751561208295527719>div>div>table>tbody>tr>td>a"));
System.out.println("Your total list elements are :" +list.size());
for(WebElement wb : list)
{
System.out.println(wb.getText());
}
}
}


Output :

Manual Testings Introduction
Definitions of Manual Testings
Defect Clustering in Software Testing
Bug Life Cycle & Reviews
Level of Testing
TEST CASE, TEST PLAN & RTM
Manual test Cases for Pen
Manual test cases for Email
ISTQB Practice set
Important Unix Command for Software Tester
Testings Myth
Agile Methodology
Windows & Linux Shortcut keys
Test Strategy in Software Testing
Finance Testing Basics
Mobile Test
Effort Estimation Technique
Java Script Basics
How to test Login page & Date fields manually
Technical Tips
Function in Javascript
Discussion Forum
Download e_Books
Professional Ethics
Aptitude Tricks
English Speaking Tutorials

Wednesday, 21 February 2018

Overview of Webservice




What is webservices ?


It's a simple xml based information exchange system, which uses internet for direct interaction between applications.

Watch Video


Components of webservice :
SOAP : Simple object access protocol
UDDI : Universal description and discovery integration.
WSDL :web services descriptive language.
Note : WSDL is a language , used by UDDI.
WSDL(Web Services Description Language)
WSDL is a language for describing web services and how to access them.
ESDL is written in xml.


What is SOAP ?
It is technology which allow communication between different languages. It allow us to pass the data over the internet in easy way.

A simple definition :
SOAP stands for Simple Object Access Protocol.
SOAP can interact with other programming language applications.
It is a just protocol which is XML Based for accessing web services over the internet.
It is recommended by W3C for communication between two application over the network.

Feature of SOAP :
1).It is a communication protocol designed to communicate via internet.
2).It can extend HTTP fro XML messaging.
3).It provide data transport for web services.
4).It can exchange complete documents or call a remote procedure.
5).It can be used for broadcasting a message.
6).It is both platform and language independent.
7).It is the XML way of defining what information is sent and how.
8).It enables the client applications to easily connect to remote services and invoke remote methods.


What is SOAP Message ?
SOAP Messages are just like post-box letter, in letter we have english text and in SOAP message we have XML.
As post-box have envelope, address, message, sender details etc. same in SOAP it have envelope, header, body & fault.

A SOAP message is an ordinary XML document containing the following elements −
Envelope − Defines the start and the end of the message. It is a mandatory element.
Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.
Body − Contains the XML data comprising the message being sent. It is a mandatory element.
Fault − An optional Fault element that provides information about errors that occur while processing the message.

SOAP Message Structure

What is WSDL ?

WSDL : Stands for Web Service Description Language
1).It is a bese file which is used to describr web service and how to access them.
2).It is written in XML
3).WSDL is the document in XML. Which describe the webservice, the location of that webservice and operations exposed by webservices.
4).WSDL is written in simple XML.


Example of WSDL:-

Click Here or open below link in your browser
http://www.webservicex.com/globalweather.asmx?WSDL

WSDL have following major elements :-


type :Describe the data type used by webservices.
message :Messages used by web services.
porttype :Operation performed by web service.
binding :Communication protocols used in web service.

Advantage of SOAP :
SOAP has its own security known as WS Security.
Language and platform independent.
Disadvantage of SOAP :
It support only XML format, it has many standards which we have to follow while working with SOAP UI so that the reason it is slow.
It works with WSDL file onle so we can not use other format like JSON, header , Cookies and so on.



What is REST ?
RESTFUL WEB SERVICES :
REST stands for Representational State Transfer

It is platform dependent
It support multiple format like Json, HTML, XML, Plain text file too.
It is fast as compared to SOAP.
It is not a protocol like SOAP it is just a architectural design.



How WebServices works ?


A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and SOAP.
A web service takes the help of −
XML to tag the data
SOAP to transfer a message
WSDL to describe the availability of service.

OR In another way
Used XML for tagging >> Transfer it to SOAP >> WSDL to get the availabilities of services.

A simple definition: A web service is a function that can be accessed by other programs over the web (Http). To clarify a bit, when you create a website in PHP that outputs HTML its target is the browser and by extension the human being reading the page in the browser. A web service is not targeted at humans but rather at other programs.


Example: I can go to maps.google.com, and type in my home address, and see a map of where I live in my browser.
But what if you were writing a computer program where you wanted to take an address and show a pretty map, just like Google maps?
Well, you could write a whole new mapping program from scratch, OR you could call a web service that Google maps provides, send it the address, and it will return a graphical map of the location, which you can display in your program.

API vs WebService

API and web service both used for communication.
The only difference is that a Web service facilitates interaction between two machines over a network. An API acts as an interface between two different applications so that they can communicate with each other. An API is a method by which the third-party vendors can write programs that interface easily with other programs.

Summary:

1. All Web services are APIs but all APIs are not Web services. as all tigers are cats but not all cats are tiger

2. Web services might not perform all the operations that an API would perform.

3. A Web service uses only three styles of use: SOAP, REST and XML-RPC for communication whereas API may use any style for communication.

4. A Web service always needs a network for its operation whereas an API doesn’t need a network for its operation.

SOAP Vs REST


SOAP is Simple Object Access Protocol
Request and Response > XML Format
Uses Web Services and more secure.

SOAP
REST
SOAP is a ProtocolREST is an architechtral style
SOAP can not use REST beacuse it is a protocolREST can use SOAP web service because it is a concept and can use any protocol like HTTP, SOAP
SOAP uses services interfaces to expose the business logicREST uses URI to expose business logic
SOAP defines standars to be strictly followedREST does not define too much standard like SOAP
SOAP Requires more bandwidth and resource than RESTREST requires less bandwidth and resource than SOAP
SOAP defines its own securityRESTful web services inherits security measures from the underlying transport
SOAP permits XML data format onlyREST permits different data format such as Plain text, HTML,XML, JSON etc.



Representational State Transfer,
Each URI is representational of some object.
Uses Http get/post/put/delete and uses XML/json/html format
Totally stateless and light weight than soap
Not a protocol rather a architechtural style.



Advantange of REST Services over SOAP Services :

1).Rest Services are light weighted
Means less data transfer between client and server machine, ultimately need less bandwidth and fast.
in non-technical word : SOAP is just like post-office letter/courier where REST is just like post-card.

2).In case of SOAP Service, we can access complete application by using WSDL but in case of REST we can access only 1 functionality(Resource) by using URI, no need to access complete application.
Advantange for service provider is that they can sell complete application as well as only part of application, it will bring more small customer to it.

3).Soap Support only XML format for data exchange. Rest support HTML, XML, JSON , plain text, PDF etc.

4).SOAP service mainly support GET but Restful services uses for main HTTP methods :
a).GET to retrieve resource
b).POST to create resource
c).PUT to update resource
d).Delete to delete resource

5).SOAP defines standards(W3C) to be strictly followed(Which will take more time to develop, test and use) but REST does not define too much standards like SOAP.

What is URI ?

URI : Uniform Resource Identifier
Identifyng documents using a short of numbers, letters and symbol.


URL and URN A URN(Uniform Resource Name) ia an internet resource with a name.

Example of URI :
http://www.thomas-bayer.com/sqlrest/CUSTOMER
http://www.thomas-bayer.com/sqlrest/CUSTOMER/2
http://www.thomas-bayer.com/sqlrest/CUSTOMER/3

WSDL Vs WADL

WSDL : The web service description language(WSDL) is an XML vocabulary used to describe SOAP-based web services.
WSDL files that we will be using for SOAP based web services only.
It's major elements are :
Definition : root element of all WSDL documents, It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.
Datatype : The data types to be used in the messages are in the form of XML schemas.
Message : It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.
Binding : It is the concrete protocol and data formats for the operations and messages defined for a particular port type.
Operation : It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.
Port : It is a combination of a binding and a network address, providing the target address of the service communication.
Service : It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.



WADL : The web application descrition language(WADL) is an XML vocabulary used to describe RESTful web services and XML vocabulary for expressing the behaviour of HTTP resources.
main porpose to define the contact.


What is SOAP UI?


Soap UI is an open-source tool used for functional and non-functional testing,widely used in web-services testing.


SOAP UI important feature


1).It is capable of performing the role of both client and service.
2).It enables the users to create functional and non-functional tests quickly and in an efficient manner using a single environment.
3).It is licensed under the terms of the GNU Leaser General Public Licence.
4).It is purely implemented wing JAVA platform.
5).It supports Windows, Mac, multiple Linux dialects.
6).It allows testers to execute automate functional, regression, compliance and load tests on different WEb API.
7).It supports all the standard protocol and technologies to test all kind of APIs.

1).Soap UI is a tool from Samrtbear mainly for functional testing but it can also be used for non functional testing like performance, security of web services.

2).Web services can be created either by SOAP or REST method, we can work with both.

3).There are two version of SOAP UI in market :
SOAP-UI free
SOAP-UI Pro paid.

WebService

1). Webservice is the type of application or software component which does not provide any GUI for user to interact.

2). We can interact that kind of application passing input to specified XML format and receiving result in XML.

3). Webservive use HTTP protocol to communicate wth web service.

4).Web services are powered by XML and thee other core technologies: WSDl, SOAP and UDDI.

Type of WebService


SOAP Services (WSDL File)
REST Services (WADL File, URI)


Demo Soap Services
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

WorkSpace

1).In Soap UI first we need to create a workspace.
2).Workspace is a place where all our projects will be saved.
3).Workspace is a single XML file, we have multiple projects in a sigle workspace.
4).It is Simillar like Domain, we can have multiple projects in a single domain.



How to download and install the SOAP UI


navigate to below url :
https://www.soapui.org/downloads/soapui.html
or click here

Click here to download from drive







Tuesday, 20 February 2018

HTTP Request and HTTP Response

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-6658533981545355", enable_page_level_ads: true }); </script>


Hello Friends,

Before starting the API Testing a tester must know what is HTTP Request and HTTP response, so this article mainly cover :
HTTP Request
HTTP Response

The HTTP Protocol :

HTTP : Hypertext Transfer Protocol

The HTTP is an application layer protocol(OSI Model) that allows web-based applications to communicate and exchange data.


OSI Layers are as below:
Application
Presentation Session
Transport
Network
Data Link
Physical

OSI model in detailed view :





What is HTTP?


The HTTP is the messenger of the web
It is a TCP/IP based protocol
It is used to deliver content for example images, videos, audios, documents etc.
The computer that communicate via the HTTP must speak the http protocol



Three Important things about HTTP


1). HTTP is connectionless means after making the request, the client disconnect from the server, then when the response is ready the server re-establish the connection again and deliver the response.
2). The HTTP can deliver any sort of data, as long as the two computers are able to read it.
3). The HTTP is a stateless means the client and server know about each other just during the current request, it is closes and the two computers want to connect again, they need to provide information to each other anew, and the connection is handled as the very first one.

Key points :


1).The HTTP is a TCP/IP based application layer protocol that allows web based applications to communicate and exchange data.
2).The computers that communicate via the HTTP must speak the http protocol.
3). The http is stateless, connectionless and can deliver any data.
4).We use the http protocol bacause it is a convenient way to quickly and reliably move data on the web.
5). The request response cycle works on the web via http messages.
6). A http message contains three sections the start line, the header and the body.
7).The http request message differs from the http response messages.


Cycle of HTTP Request & Response





HTTP Request :

An HTTP client sends an HTTP request to a server and basically this request is a packet of information.
This packet ave binary data sent by the client to the server.


HTTP Request contains following three things :


1). Request Line
2). zero or more header (General|Request|Entity) fields followed by CRLF
and an empty line(i.e. a line with nothing preceding the CRLF)
indicating the end of header fieds
3). Message body of request (Optionally)



Two HTTP Request Methods:

GET and POST

Two commonly used methods for a request-response between a client and server are: GET and POST.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource



Request line have Request Method, Request URI, HTTP Protocol

Request Header : In the request section, whatever follows Request Line till before Request Body everything is a Header.
Headers are used to pass additional information about the request to the server.

Request Body is the part of the HTTP Request where additional content can be sent to the server.
For example, a file type of JSON or XML.


Let's better understand by below Image :




HTTP Response :


After successfully receiving and interpreting a request message, server responds with a HTTP response message.
This response is the packet of information sent by server to the client.
As like HTTP Request, HTTP Response also have three things :

1).A status Line
2).Zero or more header (Genreal|Response|Entity) fields followed by CRLF
An empty line (i.e. a line with nothing preceding the CRLF)
indicating the end of the header fields
3). Message Body (optionally)


Status line has , HTTP Protocol version, Status code like 200, and Status message as OK,
Response header, Response Header also contains zero or more Header lines. However, it is very uncommon to have zero Headers in the response. Lines just after the Status Line and before the Response Body are all Response Headers lines.
Response Body , Response Body contains the resource data that was requested by the client.
Note: Response Body contains text in JSON format, as one of the Response headers suggested.
can better understood by below image :




HTTP Staus code :


1xx Informational response :
100 Continue
101 Switching Protocol
102 Processing
103 Early Hints

2xx Success :
200 OK
201 Created
202 Accepted
203 Non-Autoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reorted
226 IM Used

3xx Redirection :
300 Multiple choices
301 Moved Permanently
302 Found
303 see other
304 Not Modified
305 Use Proxy
306 Switch Proxy
307 Temporary Redirect
308 Permanent Redirect

4xx Client errors :
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 URI Too Long
415 Unsupported Media Type
416 Range Not Satisfiable
417 Expectation Failed
418 I'm a teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
451 Unavailable For Legal Reasons

5xx Server errors :
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates
507 Insufficient Storage
508 Loop Detected
510 Not Extended
511 Network Authentication Required

Click here for next topic

click here for previous topic

API Testing Overview







API TESTING OVERVIEW

Hello Friends,

In this article , i will describe that what is API? what is API Testing? and an overview of API.



What is API? (Application Programming Interface)


API is a software intermediary that use to allow two applications to talk to each other,
basically an API specifies how software components should interact.
It consists of a set of routines, protocols and tools for building the Software Application.
OR in simple words
API essentialy a library of functions, data structure and classes used by the developer to perform a specific task such a drawing a window and posting a comment etc.


Example of API :


Each time when you use an app like Twiiter, Facebook, send an instant message, or check the weather on your phone, you are using an API.

When we use an applicaton on our mobile phone, the application connects to the internet and sends data to a server, then the server retrives that data, interprets it, perform the necessary actions and sends it back to our phone.
The application then interprets that data and presents you with the information you wanted in a readable way.
This is that an API is - all of this happens via API.

Popular API Examples :

Google Maps API : Google Maps APIs lets developes embed Google Maps on weboage using a JavaScript or Flash Interface.

YouTube API : Google's APIs lets developers integrate YouTube videos and functionality into websites or applications.

Twitter APIs: Twitter offers two APIs. The REST API allows developers to access core Twitter data and the Search API provides methods for developers to interact with Twitter Search and trends data.

Amazon Product Advertising API: Amazon's Product Advertising API gives developers access to Amazon's product selection and discovery functionality to advertise Amazon products to monetize a website.

What is API Testing ?

As like other kinds of testing, API testing also is intended to reveal bugs : inconsistencies or deviations from the expected behaviour.
Continuous testing is also very important to make sure it continues to work when the public has access to it.
API testing is one of the most challenging parts of the chain of software and QA testing because it works to assure that our digital lives run in an increasingly seamless and efficient manner.
API testing as a part of integration testing to determine if they meet expectations for functionalit, reliability, performance and security.

let's discuss on Three layer Software Architecture :

Presentation layer: This layer contains the user oriented functionality responsible for managing user interaction with the system, and generally consists of components that provide a common bridge into the core business logic encapsulated in the business layer.

Business layer: This layer implements the core functionality of the system, and encapsulates the relevant business logic. It generally consists of components, some of which may expose service interfaces that other callers can use.

Data layer: This layer provides access to data hosted within the boundaries of the system, and data exposed by other networked systems; perhaps accessed through services.



Api testing is mainly exist on the business logic layer of the software architecture.
Remember : Api testing won't focus on the look and feel of an application.

Important Point : API Testing is not either black box or white box basically its both black and white.

API testing is now considered critical for automation testing because APIs now serve as the primary interface to application logic and because GUI tests are difficult to maintain with the shortrelease cycles and frequent changes commonly used with agile Software Development and Devops.

Types of API testing
API testing typically involves the following practice :
Unit Testing
Functional Testing : Incluse test case definition, execution, validation and regression testing.
Load testing
Runtime error detection : Monitoring an application the execution of automated or manual tests to expose problems such as race conditions, exceptions and resource leaks.
Security testing : Include penetration testing and fuzz testing as well as validation authentication, encryption and access control.
Web UI testing
Interoreability testing -(SOAP only) checking conformance to web services Interoperability profiles.
Compliance testing (SOAP only)

API Architecture

API Call Collector
1). HTTP Header
2). HTTP Request
3). Status code/response code

HTTP header
a) Automatization
b) Response Time

HTTP request
a. CONNECT
b. DELETE
c. GET
d. HEAD
e. OPTIONS
f. POST
g. PUT

Response code like 404 (Not Found), 200(OK) etc.


Types of Web Service

1). SOAP (Simple Object Access Protocol)
2). REST (Representational state transfer)
3). XML-RPC
4). JSON-RPC

Popular API Testing Tools :
SOAP UI
SWAGGER (Manual API Testing)
POSTMAN
API Studio
Amazon webServices
KONG
BLOCKSPRING
GALILEO
API GARAGE
SWAGGER
APIBoard

Advantage of API Testing


Test of core functionality
Test Quality
Faster Release
Test coverage with application
Access to application without user interface
Protection from malicious code and breakage
Time Efficiency Vs. Functional and Validation testing
Cost Effective/Reduce Testing cost
Technology independent.. etc

Types of bugs expected :
Wrong status code
API validation
Components (module) not interacting as expected
HTTPS request are not working.


Difference between Unit Testing and API Testing
UNIT Testing API Testing
Owned by development Owned by test
Limited in Scope Broader in scope
Mocked dependencies Mocked and real dependencies
Does it work by itself Does it play well with others
Usually ran before check-in Ran after the build created



API Test Design Principles

Robust automated test cases generally have 5 stages of API test design
1).Setup : Initialize data, create objects, start services etc.
2).Execution : Steps to exercise API or scenario, also logging
3).Verification : Oracles to evaluate execution outcome
Note : Oracles are messages function usally used to compare actual result with expected results
4).Reporting : pass, fail or blocked
5).Clean up : Pre-test state.


Key Points:

API testing benefits both the development and testing organization.
API testing is both a black and white box activity
Find some types of bugs more efficiently but not find all bugs
Doesn't evaluate "look and feel"
Can change focus of GUI automation
Not for everyone.



Approach of API Testing
1).First understand the funcationality of your API program and find the scope of this program.
2). Then simply apply your testing techniques like error guessing, input parameters , boundary value etc.
3). Now time have come to execute your test case & compare the result with expected results.

Click Here for Next Topic









Tuesday, 13 February 2018

How To Handle Tabs in selenium




Hello Friends,

In this article , i will describe that how to handle the Tabs in selenium.
So we will cover below scearios :

For Video part 1:

Click here



For Video part 2:

Click here



Scenario :1-
Open the browser & enter Url Open a new tab
Hit a url in new tab
perform some operation in new tab
come back to main tab

Scenario :2-
Open the browser & enter Url
click some link which will open the new tab
switch to newly opened tab
perform some operation
come back to main tab
Scenario :3-
Open the browser & enter Url click on link which will open the new tab
switch to newly opened tab
close newly opened tab only
perform some operation in your main tab

So, here we will write some simple code to do these operations :-

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class RealTabdemo
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000); }
@Test
public void h() throws InterruptedException, AWTException
{
//driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"t");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
Robot rbt = new Robot();
rbt.keyPress(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_T);
rbt.keyRelease(KeyEvent.VK_CONTROL);
rbt.keyRelease(KeyEvent.VK_T);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
String originalHandle = driver.getWindowHandle();
ArrayList tabs2 = new ArrayList (driver.getWindowHandles());
System.out.println(tabs2.size());
driver.switchTo().window(tabs2.get(1));
driver.get("http://www.onlineifsccodebank.com");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//*[@id='txtIFSCCode']")).sendKeys("ALLA0211921");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
try
{
driver.findElement(By.xpath(".//*[@id='btnSearch']")).click();
}
catch(Exception e)
{
System.out.println(e.getMessage());
driver.findElement(By.cssSelector("#btnSearch")).click();
}
driver.close();
driver.switchTo().window(tabs2.get(0));
driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/div[1]/table/tbody/tr[1]/td[2]/a/img")).click();
Thread.sleep(3000);
driver.switchTo().window(tabs2.get(1));
driver.findElement(By.xpath(".//*[@id='post-body-7737945062927568046']/table[1]/tbody/tr[1]/td[1]/a")).click();
for(String handle : driver.getWindowHandles())
{
if (!handle.equals(originalHandle))
{
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(originalHandle);
}
}





Another Example :
Scenarios :
Open the browser & navigate to URL
Open the new Tab by using Robot class
open new URL in new tab
Pass driver control in new tab
Perform some operation in new tab
close the new Tab
pass the driver control back to main parent tab


Here is the sample code, where we will open the browser & hit the URL
Then open a new tab, and open a new Url in new tab
now will perform operation in new tab
close the new tab & come back to parent tab


Another Example :

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Tabtest
{
WebDriver driver;
@BeforeTest
public void h() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void g() throws AWTException, InterruptedException
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
Thread.sleep(3000);
String windowhandle = driver.getWindowHandle();
ArrayList tabs = new ArrayList(driver.getWindowHandles());
System.out.println("Total tabs are : " +tabs.size());
driver.switchTo().window((String) tabs.get(1));
driver.navigate().to("http://www.onlineifsccodebank.com");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[@id='txtIFSCCode']")).sendKeys("UTIB0003109");
driver.findElement(By.xpath(".//*[@id='btnSearch']")).click();
driver.close();
driver.switchTo().window(windowhandle);
Thread.sleep(4000);
}
@Test(priority = 1)
public void I() throws InterruptedException
{
String originalHandle = driver.getWindowHandle();
driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/div[1]/table/tbody/tr[1]/td[2]/a/img")).click();
ArrayList tabs2 = new ArrayList(driver.getWindowHandles());
System.out.println("Total tabs are : " +tabs2.size());
driver.switchTo().window((String) tabs2.get(1));
Thread.sleep(4000);
driver.findElement(By.xpath(".//*[@id='post-body-7737945062927568046']/table[1]/tbody/tr[1]/td[1]/a")).click();
Thread.sleep(4000);
for(String handle : driver.getWindowHandles())
{
if (!handle.equals(originalHandle))
{
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(originalHandle);
}
}




Tuesday, 6 February 2018

Send Reports Automatically to Email using Maven from Eclipse




Hell Friends,

In this article we will discuss

How to Send Reports Automatically to Email using Maven from Eclipse by Post-Man plugin



For Video :

Click here

This is very simple, you just need to add some plugin & remaining things will be same.
So steps will be as below :
Step 1 : Create a Maven Project.
Step 2 : Add Dependency as below in your POM.xml file.
Step 3 : Update the project.
Step 4 : Convert your Execution file to TestNG xml file & place it in main source folder(if using below plugins).
Step 5 : Set email address & report path.
Step 6 : Now Run your POM.xml file.

To Download the complete plugin in notepad click the below link :

click here



Alternatively, one can copy the below plugin & paste in his Maven Pom.xml file.

<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>Report_demo</groupId>
<artifactId>Report_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<suiteXmlFile>src/main/resources/testng.xml</suiteXmlFile>
</properties>
<dependencies>
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>ch.fortysix</groupId>
<artifactId>
maven-postman-plugin</artifactId>
<executions>
<execution>
<id>send a mail</id>
<phase>test</phase>
<goals>
<goal>send-mail</goal>
</goals>
<inherited>true</inherited>
<configuration>
<!-- From Email address -->
<from>cchauhan281188@gmail.com</from>
<!-- Email subject -->
<subject>Test Automation Report</subject>
<!-- Fail the build if the mail doesnt reach -->
<failonerror>true</failonerror>
<!-- host -->
<mailhost>smtp.gmail.com</mailhost>
<!-- port of the host -->
<mailport>465</mailport>
<mailssl>true</mailssl>
<mailAltConfig>true</mailAltConfig>
<!-- Email Authentication(USername and Password) -->
<mailuser>Enter email id here</mailuser>
<mailpassword>Enter password here</mailpassword>
<receivers>
<!-- To Email address -->
<receiver>cchauhan32@gmail.com</receiver>
</receivers>
<fileSets>
<fileSet>
<!-- Report directory Path -->
<directory>C://workspace//SendMavenEmail//Reports</directory>
<directory>E://java_oxygen//Report_demo//Reports</directory>
<includes>
<!-- Report file name -->
<include>TestReport.html</include>
</includes>
<!-- Use Regular Expressions like **/*.html if you want all the html files to send-->
</fileSet>
</fileSets>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>



Here is the sample code

package com.lang.Execution;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportTest
{
WebDriver driver;
ExtentReports report;
ExtentTest logger;
@BeforeTest
public void navigate() throws InterruptedException, IOException
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
report=new ExtentReports("./Reports/TestReport.html");
}
@Test(priority = 0)
public void title()
{
logger=report.startTest("Verifytitle");
logger.log(LogStatus.INFO, "test started ");
System.out.println("Your Title is :" + driver.getTitle());
String title = driver.getTitle();
if(title.equalsIgnoreCase(" Online Software Testing: Software Testing"))
{
logger.log(LogStatus.PASS, "Test Verified");
}
else
{
logger.log(LogStatus.FAIL, "Test Failed");
}
report.endTest(logger);
//Flush the data to report
report.flush();
}
@Test(priority = 1)
public void clicklink(){
//Create object for Report with filepath
//report=new ExtentReports("./Reports/TestReport.html");
//Start the test
logger=report.startTest("Verifylink");
//Log the status in report
logger.log(LogStatus.INFO, "Test started ");
driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/div[1]/table/tbody/tr[6]/td[1]/a/img")).click();
//Pass the test in report
logger.log(LogStatus.PASS, "Link Verified");
//End the test
report.endTest(logger);
//Flush the data to report
report.flush();
}
}







Tags :

how to send report through email in selenium webdriver,Sending Selenium Reports through mail,
Advance Selenium Reporting- Selenium Webdriver tutorial How to Send a Report via Email in selenium,
How to generate and send HTML reports using Selenium WebDriverSend Reports Automatically to Email using Maven from Eclipse
Robotically Send Test Reports via Mail Using Maven Postman PluginHow to send Test result to email using maven by postman plugin
how do i send a email test report from maven,How to send an automated email with test reports using Maven and TestNG,

Core Java Interview Questions for Selenium tester




Hell Friends,

In this article we will discuss about Java interview Questions for Selenium Tester :

0.What is Java?
Java is a programming language and computing platform first released by Sun MicroSystems in 1995.

1. What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

2. Does Java support multiple inheritance?
Java doesn't support multiple inheritance.

3. What is the most important feature of Java?
Java is a platform independent language.

4. What is difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

5. What are instance variables?
Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

6. What is a pointer and does Java support pointers?
Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

7. What is the return type of the main() method?
Main() method doesn't return anything hence declared void.

8. What are local variables?
Local variables are those which are declared within a block of code like methods. Local variables should be initialized before accessing them.

9. Is Java a pure object oriented language?
Java uses primitive data types and hence is not a pure object oriented language.

10. Is JVM platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

11. Can a main() method be overloaded?
Yes. You can have any number of main() methods with different method signature and implementation in the class.

12. What is the base class of all classes?
java.lang.Object

13. What do you mean by platform independence?
Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

14. Are arrays primitive data types?
In Java, Arrays are objects.

15. What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

16. Does the order of public and static declaration matter in main() method?
No. It doesn't matter but void should always come before main().

17. What is the impact of declaring a method as final?
A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation.

18. Can a class be declared as protected?
A class can't be declared as protected. only methods can be declared as protected.

19. How to define a constant variable in Java?
The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also. static final int PI = 2.14; is an example for constant.

20. Which package is imported by default?
java.lang package is imported by default even without a package declaration.

21. What is the argument of main() method?
main() method accepts an array of String object as argument.

22. Can a source file contain more than one class declaration?
Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.

23. What is the access scope of a protected method?
A protected method can be accessed by the classes within the same package or by the sub classes of the class in any package.

24. Can a class declared as private be accessed outside it's package?
Not possible.

25. Why is the main() method declared static?
main() method is called by the JVM even before the instantiation of the class hence it is declared as static.

26. What is the purpose of declaring a variable as final?
A final variable's value can't be changed. final variables should be initialized before using them.

27. What is a package?
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

28. Can a main() method be declared final?
Yes. Any inheriting class will not be able to have it's own default main() method.

29. I don't want my class to be inherited by any other class. What should i do?
You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.

30. Should a main() method be compulsorily declared in all java classes?
No not required. main() method should be defined only if the source class is a java application.

31. When will you define a method as static?
When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

32. What is the importance of static variable?
static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

33. How is final different from finally and finalize()?
final is a modifier which can be applied to a class or a method or a variable. final class can't be inherited,final method can't be overridden and final variable can't be changed.
finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment. finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

34. I want to print "Hello" even before main() is executed. How will you achieve that?
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

35. Can we declare a static variable inside a method?
Static variables are class level variables and they can't be declared inside a method. If declared, the class will not compile.

36. Can a abstract class be defined without any abstract methods?
Yes it's possible. This is basically to avoid instance creation of the class.

37. Can you give few examples of final classes defined in Java API?
java.lang.String, java.lang.Math are final classes.

38. Can a abstract class be declared final?
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

39. Can you create an object of an abstract class?
Not possible. Abstract classes can't be instantiated.

40. What are the restriction imposed on a static method or a static block of code?
A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

41. Can a Class extend more than one Class?
Not possible. A Class can extend only one class but can implement any number of Interfaces.

42. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

43. Can a class be defined inside an Interface?
Yes it's possible.

44. Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

45. What is use of a abstract variable?
Variables can't be declared as abstract. only classes and methods can be declared as abstract.

46. Can an Interface be defined inside a class?
Yes it's possible.

47. What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

48. Can an Interface be final?
Not possible. Doing so so will result in compilation error.

49. Can an Interface implement another Interface?
Interfaces doesn't provide implementation hence a interface cannot implement another interface.

50. Why does Java not support operator overloading?
Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.

51. Is there any difference between an argument and a parameter?
While defining methods, you pass variables which you refer as parameters. And when you call these methods and pass values for the variables then they are phrased as arguments.

52. How your program would behave if you declare the main method as private?
It would get compiled correctly but will throw the error "Main method not public." at runtime.

53. Q: What difference you see between pass by reference and pass by value in Java?
Pass by reference indicates, passing the address itself rather than passing the value. Pass by value means is giving a copy of the value.
Example : Actions action = new Actions(driver);

54. Can you compile a Java class successfully without having the main method?
Yes, we can compile, but it won't run. The
method works as the startup function for a Java class, and the JVM calls it for the program execution.

55.What do you make of System, out and in the function System.out.println()?
System -> A predefined final class,
out -> PrintStream object and,
The -> built-in overloaded method of the out object.

56.Q: How would you prove that an array is not null but is empty?
Call the . It will print 0. That suggests that the array is empty. If it would've been null then, it would've thrown a on calling the .

57. Q: What do you understand of Garbage Collection and how to call it explicitly?
If the object is no longer belong to any variable, Java automatically reclaims the memory. This process is known as garbage collection. You can use the method to call it explicitly.
For more :

Click here