Select Page

Category Selected: Latest Post

280 results Found


People also read

AI Testing

Functional Testing: Ways to Enhance It with AI

Automation Testing

Scaling Challenges: Automation Testing Bottlenecks

Accessibility Testing

Online Accessibility Checker: How Effective Are They Really

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility
Read Data from XML by Using Different Parsers in Java

Read Data from XML by Using Different Parsers in Java

Reducing the complexity of any process is always the key to better performance, similarly parsing the XML data to obtain a readable format of that XML file that we humans can understand is also a very important process. A simple equivalent to this parsing process would be the process of language translation. Let’s take the example of two national leaders discussing an important meeting. They could either choose to use a common language like English or talk in the languages they are comfortable with and use translators to solve the purpose. Likewise, the XML will be in a format that is easily understood by a computer, but once the information has been parsed, we will be able to read data from XML and understand it with ease.

As one of the leading QA companies in the market, we use different parsers based on our needs and so let’s explore which parser would be the perfect match for your need by understanding how they work. But before we explore how we can read data from XML, let us get introduced to XML first as there might be a few readers who may not know much about XML.

An Introduction to the XML:

XML stands for Extensible mark-up Language, and it’s primarily used to describe and organize information in ways that are easily understandable by both humans and computers. It is a subset of the Standard Generalized Mark-up Language (SGML) that is used to create structured documents. In XML, all blocks are considered as an “Element”. The tags are not pre-defined, and they are called “Self-descriptive” tags as it enables us to create our own customized tags. It also supports node-to-node interaction to fill the readability gap between Humans and Machines.

XML is designed to store and transfer data between different operating systems without us having to face any data loss. XML is not dependant on any platform or language. One can say that XML is similar to HTML as it neither acts as the frontend nor as the backend. For example, we would have used HTML to create the backend code, and that code would be passed to the frontend where it is rendered as a webpage.

Prerequisite:

There are a few basic prerequisites that should be ready in order to read data from XML, and we have listed them below,

1. Install any IDE(Eclipse/Intellij )

2. Make sure if Java is installed

3. Create a Java project in IDE

4. Create an XML file by using .xml extension

XML file creation:

So the first three steps are pretty straightforward, and you may not need any help to get it done. So let’s directly jump to the fourth and final prerequisite step, where we have to create an XML file manually in our Java project.

Navigate to the File tab in your IDE

– Create a new file

– Save it as “filename.xml”

The XML file will display under your Java project. In the same way, we can create the XML file in our local machine by using the .xml file extension. Later, we can use this XML file path in our program for parsing the XML. Let’s see the technologies for parsing the XML.

XML Parse:

XML parsing is nothing but the process of converting the XML data into a human-readable format. The XML parsing can be done by making use of different XML Parsers. But what do these parsers do? Well, parsers make use of the XSL Transformation (XSLT) processor to transform the XML data to a readable format and paves the way for using XML in our programs. The most commonly used parsers are DOM, SAX, StAX, Xpath, and JDOM. So let’s take a look at each parses one-by-one..

Using DOM Parser to Read data from XML:

DOM stands for Document Object Model. DOM is a parser that is both easy to learn and use. It acts as an interface to access and modify the node in XML. DOM works by building the entire XML file into memory and moving it node by node in a sequential order to parse the XML. DOM can be used to identify both the content and structure of the document. But the setback that comes with DOM is that it is slow and consumes a large amount of memory because of the way it works. So DOM will be an optimal choice if you are looking to parse a smaller file and not a very large XML file as everything in DOM is a node in the XML file. Let’s see how to parse the below XML by using the DOM parser.

Here is the XML File that we need to parse:

<?xml version = "1.0"?>
<Mail>
        <email Subject="Codoid Client Meeting Remainder">
    <from>Priya</from>
    <empid>COD11</empid>
    <Designation>Software Tester</Designation>
    <to>Karthick</to>
    <body>We have meeting at tomorrow 8 AM. Please be available
    </body>
        </email>
    <email Subject="Reg:Codoid Client Meeting Remainder ">
        <from>Kartick</from>
        <empid>COD123</empid>
        <Designation>Juniour Software Tester</Designation>
        <to>Priya</to>
        <body>Thanks for reminding me about the meeting. Will join on time</body>
    </email>
</Mail>
DOM Parser:
package com.company;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class DOMParser {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        try {
            File file = new File("E:\\Examp\\src\\com\\company\\xmldata.xml");
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
            Document doc = builder.parse(file);
            doc.getDocumentElement().normalize();
            System.out.println("Root element::  " + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("email");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                System.out.println("\nCurrent Element :" + nNode.getNodeName());
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("Email Subject : "
                            + eElement.getAttribute("Subject"));
                    System.out.println("From Name : "
                            + eElement
                            .getElementsByTagName("from")
                            .item(0)
                            .getTextContent());
                    System.out.println("Designation : "
                            + eElement
                            .getElementsByTagName("Designation")
                            .item(0)
                            .getTextContent());
                    System.out.println("Employee Id : "
                            + eElement
                            .getElementsByTagName("empid")
                            .item(0)
                            .getTextContent());
                    System.out.println("To Name : "
                            + eElement
                            .getElementsByTagName("to")
                            .item(0)
                            .getTextContent());
                    System.out.println("Email Body : "
                            + eElement
                            .getElementsByTagName("body")
                            .item(0)
                            .getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

We have created a DocumentBuilderFactory API to produce the object trees from XML, after which we’ve also created a document interface to access the XML document data. As stated earlier, the node is the base datatype for DOM here. From the code, we can see that the getDocumentElement() method will return the root of the element, and the getElementsByTagName() method will return the value of that particular tag.

Using the SAX Parser to Read data from XML:

The SAX parser is a simple event-based API that parses the XML document line-by-line using the Handler class. Everything in XML is considered to be “Tokens” in SAX. Unlike the DOM parser that we saw earlier, SAX does not load the entire XML file into memory. It also doesn’t create any object representation of the XML document. Instead, it triggers events when it encounters the opening tag, closing tag, and character data in an XML file. It reads the XML from top to bottom and identifies the tokens and call-back methods in the handler that are invoked. Due to the top to bottom approach, tokens are parsed in the same order as they appear in the document. Due to the change in the way SAX works, it is faster and uses less memory in comparison to the DOM parser.

SAX Parser:
try{
            File file = new File("E:\\Examp\\src\\com\\company\\xmldata.xml");
            SAXParserFactory saxParserFactory= SAXParserFactory.newInstance();
            SAXParser saxParser= saxParserFactory.newSAXParser();
            SaxHandler sax= new SaxHandler();
            saxParser.parse(file,sax);

        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

In the above code, we have created an XML file and given its path in the code. The SAXParserFactory used in the code creates the new instance for that file. After that, we can create the object for the Handler class using which we parse the XML data. So we have called the handler class method by using the object. Now, let’s see how the Handler class and its method are created.

class SaxHandler extends DefaultHandler{
    boolean from=false;
    boolean to=false;
    boolean Designation= false;
    boolean empid= false;
    boolean body=false;
    StringBuilder data=null;
@Override
    public void startElement(String uri, String localName,
                             String qName, Attributes attributes){

    if(qName.equalsIgnoreCase("email")){
        String Subject= attributes.getValue("Subject");
        System.out.println("Subject::  "+Subject);
    }
    else if(qName.equalsIgnoreCase("from")){
        from=true;
    }
    else if(qName.equalsIgnoreCase("Designation")){
        Designation=true;
    }
    else if(qName.equalsIgnoreCase("empid")){
        empid=true;
    }
    else if(qName.equalsIgnoreCase("to")){
        to=true;
    }
    else if(qName.equalsIgnoreCase("body")) {
        body = true;
    }
    data=new StringBuilder();
}
@Override
      public void endElement(String uri, String localName, String qName){
      if(qName.equalsIgnoreCase("email")){
          System.out.println("End Element::  "+qName);
      }
}
    @Override
   public void characters(char ch[], int start, int length){
//    data.append(new String(ch,start,length));
        if(from){
            System.out.println("FromName::  "+new String(ch,start,length));
            from=false;
        }
        else if(Designation){
            System.out.println("Designation::  "+new String(ch,start,length));
            Designation=false;
        }
        else if(empid){
            System.out.println("empid::  "+new String(ch,start,length));
            empid=false;
        }
        else if(to){
            System.out.println("to::  "+new String(ch,start,length));
            to=false;
        }
        else if(body){
            System.out.println("body::  "+new String(ch,start,length));
            body=false;
        }
}
}

Our ultimate goal is to read data from XML using the SAX parser. So in the above example, we have created our own SAX Parser class and also extended the DefaultHandler class which has various parsing methods. The 3 most prevalent methods of the DefaultHandler class are:

1. startElement() – It receives the notification of the start of an element. It has 3 parameters which we have explained by providing the data that has to be used.

startElement(String uri, String localName,String qName, Attributes attributes)

uri – The Namespace URI, or the empty string if the element has no Namespace URI.

localName – The local name (without prefix) or the empty string if Namespace processing is not being performed.

qName – The qualified name (with prefix) or the empty string if qualified names are not available.

attributes – The attributes attached to the element. If there are no attributes, it shall be an empty attributes object.

The startElement() is used to identify the first element of the XML as it creates an object every time a start element is found in the XML file.

2. endElement() – So we have already seen about startElement(), and just as the name suggests, endElement() receives the notification of the end of an element.

endElement (String uri, String localName, String qName) 

uri – The Namespace URI, or the empty string if the element has no Namespace URI

localName – The local name (without prefix) or the empty string if Namespace processing is not being performed.

qName – The qualified name (with prefix) or the empty string if qualified names are not available.

The endElement() is used to check the end element of the XML file.

3.characters() – Receives the notification of character data inside an element.

characters (char ch[], int start, int length) 

ch – The characters.

start – The start position in the character array.

length – The number of characters that have to be used from the character array.

characters() is used to identify the character data inside an element. It divides the data into multiple character chunks. Whenever a character is found in an XML document, the char() will be executed. That’s why we append() the string to keep this data.

Using the JDOM Parser to Read data from XML:

So the JDOM parser is a combination of the DOM and SAX parsers that we have already seen. It’s an open-source Java-based library API. The JDOM parser can be as fast as the SAX, and it also doesn’t require much memory to parse the XML file. In JDOM, we even can switch the two parsers easily like DOM to SAX, or vice versa. So the main advantage is that it returns the tree structure of all elements in XML without impacting the memory of the application.

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JDOMParser {
    public static void main(String[] args) throws JDOMException, IOException {
        try{
            File file = new File("E:\\Examp\\src\\com\\company\\xmldata.xml");
            SAXBuilder saxBuilder = new SAXBuilder();
            Document doc= saxBuilder.build(file);
            System.out.println("Root element :" + doc.getRootElement().getName());
            Element ele= doc.getRootElement();
            List<Element> elementList = ele.getChildren("email");
            for(Element emailelement: elementList){
                System.out.println("Current element::  "+emailelement.getName());
                Attribute attribute= emailelement.getAttribute("Subject");
                System.out.println("Subject::  "+attribute.getValue());
                System.out.println("From::  "+emailelement.getChild("from").getText());
                System.out.println("Designation::  "+emailelement.getChild("Designation").getText());
                System.out.println("Empid::  "+emailelement.getChild("empid").getText());
                System.out.println("To::  "+emailelement.getChild("to").getText());
                System.out.println("Body::  "+emailelement.getChild("body").getText());
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

We have used the SAXBuilder class to transform the XML to a JDOM document. The getRootElement() is used to find the starting element of the XML and store all the elements from the XML to a list based on the starting element and iterate that element list. At the very end, we have used the getText() method to get the value of each attribute.

Using the StAX Parser to Read data from XML:

The StAX Parser is similar to the SAX Parser with just one difference. That major difference is that it employs 2 APIs (Cursor based API and Iterator-based API) to parse the XML. The StAX parser is also known as the PULL API, and it gets the name from the fact that we can use it to access the information from the XML whenever needed. The other standout aspect of the StAX parser is that it can read and also write the XML. Every element in the XML is considered as “Events”, and below is the code that we require for parsing the XML file using the StAX Parser.

XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader eventReader =
        factory.createXMLEventReader(new FileReader("E:\\Examp\\src\\com\\company\\xmldata.xml "));
while(eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        switch(event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        String qName = startElement.getName().getLocalPart();
        if (qName.equalsIgnoreCase("email")) {
        System.out.println("Start Element : email");
        Iterator<Attribute> attributes = startElement.getAttributes();
    String rollNo = attributes.next().getValue();
    System.out.println("Subject " + Subject);
    } else if (qName.equalsIgnoreCase("from")) {
    EmailFrom = true;
    } else if (qName.equalsIgnoreCase("empid")) {
    Empid = true;
    } else if (qName.equalsIgnoreCase("Designation")) {
    Desination = true;
    }
    else if (qName.equalsIgnoreCase("to")) {
    EmailTo = true;
    }
    else if (qName.equalsIgnoreCase("body")) {
    EmailBody = true;
    }
    break;
    case XMLStreamConstants.CHARACTERS:
    Characters characters = event.asCharacters();
    if(EmailFrom) {
    System.out.println("From: " + characters.getData());
    EmailFrom = false;
    }
    if(Empid) {
    System.out.println("EmpId: " + characters.getData());
    Empid = false;
    }
    if(Desination) {
    System.out.println("Designation: " + characters.getData());
    Desination = false;
    }
    if(EmailTo) {
    System.out.println("to: " + characters.getData());
    EmailTo = false;
    }
    if(EmailBody) {
    System.out.println("EmailBody: " + characters.getData());
    EmailBody = false;
    }
    break;
    case XMLStreamConstants.END_ELEMENT:
    EndElement endElement = event.asEndElement();
    if(endElement.getName().getLocalPart().equalsIgnoreCase("email")) {
    System.out.println("End Element : email");
    System.out.println();
    }
    break;
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
        }
}}

In StAX, we have used the XMLEventReader interface that provides the peek at the next event and also returns the configuration information.

The StartElement interface give access to the start elements in XML and the asStartElement() method returns the startElement event. It is important to note that the exception will be shown if the start element event doesn’t occur.

All character events are reported using the Characters interface. If you are wondering what would get reported as character events? The answer is that all the text and whitespaces events are reported as characters events.

The asCharacters() method returns the Characters from XML, and we will be able to get the data from XML as characters using the getData() method. Though it iterates each and every data from the XML and gives it in the form of a tree structure, it doesn’t return the start and end element events.

The EndElement class is used to point and return the end of the elements in an XML doc.

Using the Xpath Parser to Read data from XML:

The Xpath parser is a query language that is used to find the node from an XML file and parse the XML based on the query string. Now let’s take a look at an example code for better understanding.

File inputFile = new File("E:\\Examp\\src\\com\\company\\xmldata.xml");

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder dBuilder;
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            XPath xPath =  XPathFactory.newInstance().newXPath();
            String expression = "/Mail/Email";
            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
    Node nNode = nodeList.item(i);
    System.out.println("\nCurrent Element :" + nNode.getNodeName());
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("From : " + eElement.getElementsByTagName("from").item(0).getTextContent());
        System.out.println("EmpId : " + eElement.getElementsByTagName("empid").item(0).getTextContent());
        System.out.println("Designation : " + eElement.getElementsByTagName("Designation").item(0).getTextContent());
        System.out.println("TO : " + eElement.getElementsByTagName("to").item(0).getTextContent());
        System.out.println("Body : " + eElement.getElementsByTagName("body").item(0).getTextContent());
    }

In the above code, we used the XPath Factory for creating a new instance for the XPath. Then we have taken the XPath for the XML data and stored it as a String datatype. This String expression is called as “XPath Expression”.

Next, we have compiled the list of the XPath Expression by using the xPath.compile() method and iterated the list of nodes from the compiled expression using the evaluate() method.

We have used the getNodeName() method to get the starting element of the XML.

So once the XML document has been read, we would reuse the document and the XPath object in all the methods.

Conclusion

We hope you have found the parser that fits your requirement and in-process also enjoyed reading this article. So to sum things up, we have seen how each parser works to understand the pros and cons of each type. Choosing the apt parser might seem like a very small aspect when compared to the entire scale of the project. But as one of the best software testing service providers, we believe in attaining maximum efficiency in each process, be it small or big.

An Introductory Action Class Guide for Beginners

An Introductory Action Class Guide for Beginners

If you are going to test an application using Selenium WebDriver, you most definitely will face scenarios where you will be needed to trigger keyboard and mouse interactions. This is where our Action Class Guide comes into the picture. Basically, Action Class is a built-in feature provided by Selenium for simulating various events and acts of a keyboard and mouse. With the help of Action classes, you will be able to trigger mouse events like Double Click, Right Click, and many more events. The same goes for keyboards as well, you can trigger the functions of CTRL key, CTRL + different keys, and other such combinations. As one of the best QA companies, we have been able to use Action Class to its zenith by using it in various combinations as per the project needs. But before exploring such Action class implementations, let’s take a look at some basics.

Action Class Guide for MouseActions

So we wanted to start our Action Class Guide by listing some of the most frequently used mouse events available in the Action class.

click() – Clicks on the particular WebElement (Normal Left Click)

contextClick() – Right clicks on the particular WebElement

doubleClick() – Performs a double click on the WebElement

dragAndDrop (WebElement source, WebElement target) – Clicks and holds the web element to drag it to the targeted web element where it is released.

dragAndDropBy(WebElement source, int xOffset, int yOffset) – Clicks and Drag the element to the given location using offset values

moveToElement(WebElement) – Moves the mouse to the web element and holds it on the location (In simple words, the mouse hovers over an element)

moveByOffset(int xOffSet, int yOffSet) – Moves the mouse from the current position to the given left (xOffset value) and down (yOffset Value).

clickAndHold(WebElement element) – Clicks and holds an element without release.

release() – Releases a held mouse click.

Action Class Guide Keyboard Actions

Same as above, we have listed some frequently used keyboard events available in the Action class,

keyDown(WebElement, java.lang.CharSequence key) – To press the key without releasing it on the WebElement

keyUp(WebElement, java.lang.CharSequence key) – To release the key stroke on the webElement

sendkeys(value) – To enter values on WebElements like textboxes

So by including these methods, you can smoothly run your script and execute the code without any issues….

Absolutely not, we’re just kidding. We still have to gather all the action methods and execute them under the Action class.

build() – It is a method where all the actions are chained together for the action which is going to be performed.

So the above method can be used to make the actions that are to be executed ready.

perform() – It is a method used to compile and also execute the action class.
A perform method can be called alone without a build method to execute the action class methods if only one action is performed.

Action Class Guide for Performing actions

Now that we have gone through the basics, let’s find out how to implement the Action Classes in Code.

Step1:

Import the Interaction package that contains the Action Class. You can use the below line for importing,

“importorg.openqa.selenium.interactions.Actions; ”

Step2:

Create the object of the Action Class and use the Web Driver reference as the argument
Actions action = new Actions (driver)

Step3:

Once the above two steps have been completed, you can start writing your script using the Action classes and the different methods available.

Let’s proceed further and take a look at the implementation and uses of the actions available for both the mouse & keyboard.

1. SendKeys(WebElement element, value)

As stated above, this action class is mainly used to send a char sequence into the textbox. But it is also worth noting that we can use it to send the keystrokes of different key combinations likeCTRL+T, Enter, and so on.

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 java.util.concurrent.TimeUnit;
public class SendKeys {
    public static void main(String[] args) {
        WebDriver driver;        System.setProperty("webdriver.chrome.driver","D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        WebElement eleSearchBox = driver.findElement(By.cssSelector("input[placeholder='Search for products, brands and more']"));
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        action.sendKeys(eleSearchBox, "Iphone").build().perform();
        action.sendKeys(Keys.ENTER).build().perform();
        driver.close();
    }
}

By using the SendKeys method, an element is searched by the keystroke instead of clicking on the Search Button. (i.e.) We can clearly see in the code that the “Keys.Enter” is inside the Keys class that has various keystrokes available for the keys.

2. MoveToElement(WebElement element)

You might be in a position to test if an element changes color, shows some additional information, or performs the intended action when the mouse hovers over it. So let’s take a look at the code and find out how you can make it happen.

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;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class MouseHover {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://www.leafground.com/");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.scrollBy(0,170)", "");
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//img[@alt='mouseover']"))).click();
        WebElement eleTabCourses = driver.findElement(By.xpath("//a[normalize-space()='TestLeaf Courses']"));
        action.moveToElement(eleTabCourses).build().perform();
        driver.close();
    }
}

We have written the above code in a way that the code first waits for the image to become clickable. Once it loads, the image gets clicked, and the mouse hovers over the element for a second.

3. DragAndDrop(source, target)

So there are basically two types of drag and drop that we will be seeing in this Action Class Guide. This is the type of action class using which we can assign a target area where the element can be dragged and dropped. Now let’s see the code to execute the DragAndDrop action,

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.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DragAndDrop {
        public static void main(String[] args) {
            WebDriver driver;
            System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
            driver = new ChromeDriver();
            driver.get("http://www.leafground.com/");
            driver.manage().window().maximize();
            Actions action = new Actions(driver);
            driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
            driver.findElement(By.xpath("//h5[normalize-space()='Droppable']")).click();
            WebElement eleSource = driver.findElement(By.xpath("//div[@id='draggable']"));
            WebElement eleTarget = driver.findElement(By.xpath("//div[@id='droppable']"));
            action.dragAndDrop(eleSource,eleTarget).build().perform(););
            driver.close();
        }
}

For dragging an element to the dropped place, first, the locators are captured for the source and target. Following this, they are passed inside the action method using dragAndDrop.

4. DragAndDropBy(WebElement source,int xOffset, int yOffSet )

So we have already seen how to drag a drop an element within a targeted area, but what if we would like to drag and drop an element by a defined value? Let’s take a look at the code and find out how.

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.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DragAndDropOffset {
        public static void main(String[] args) throws InterruptedException {
            WebDriver driver;
            System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
            driver = new ChromeDriver();
            driver.get("http://www.leafground.com/");
            driver.manage().window().maximize();
            Actions action = new Actions(driver);
            driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
            driver.findElement(By.xpath("//img[@alt='Draggable']")).click();
            WebElement eleDrag= driver.findElement(By.xpath("//div[@id='draggable']"));
            action.dragAndDropBy(eleDrag,200,130).build().perform();
            Thread.sleep(2000);
            driver.close();
        }
    }

In the above code, we have used the DragAndDropBy method in a way that it clicks and moves the element to the offset position as specified and releases it once the target location is reached.

5. Click(WebElement element)

There is no way to test anything without being able to use the left click button. So let’s find out the code to execute this very basic and necessary functionality.

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.interactions.Actions;
public class LeftClick {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.sendKeys(eleInput, "www.codoid.com").build().perform();
        WebElement BtnSearch = driver.findElement(By.xpath("//div[@class='FPdoLc lJ9FBc']//input[@name='btnK']"));
        actions.click(BtnSearch).build().perform();
        driver.close();
    }
}

6. ContextClick(WebElement element)

Though the right-click is not used as commonly as the left click, it is still a very basic functionality every tester must know. So let’s take a look at the code to find out how to implement it.

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.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class RightClick {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://demo.guru99.com/test/simple_context_menu.html");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        WebElement eleRightClick = driver.findElement(By.xpath("//span[@class='context-menu-one btn btn-neutral']"));
        action.contextClick(eleRightClick).perform();
        driver.close();
    }
}

It is worth mentioning here that we have not used ‘build’ anywhere in the above code. Instead, we have used ‘perform’ to execute the functionality.

7. DoubleClick(WebElement element)

Just like the previous functionalities we have seen in the Action Class Guide, double-click is another basic functionality that is vital to any form of testing. So let’s jump straight to the code.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DoubleClick {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://demo.guru99.com/test/simple_context_menu.html");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        WebElement eleDoubleClick = driver.findElement(By.xpath("//button[normalize-space()='Double-Click Me To See Alert']"));
        action.doubleClick(eleDoubleClick).perform();
        driver.quit();
    }

8. KeyDown(WebElement element, Modifier Key) & KeyUp (WebElement element, Modifier Key)

CTRL, SHIFT, and ALT are few examples of modifier keys that we all use on a day-to-day basis. For example, we hold down Shift if we want to type something in caps. So when we use the KeyDown action class, it holds a particular key down until we release it using the KeyUp action class. With that said, let’s see an example code in which we have used these functionalities,

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;
public class KeyDownAndKeyUp {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.click(eleInput).build().perform();
        actions.keyDown(eleInput, Keys.SHIFT);
        actions.sendKeys("eiffel tower");
        actions.keyUp(eleInput,Keys.SHIFT);
        actions.sendKeys(Keys.ENTER);
        actions.build().perform();
        driver.close();
    }
}

So if you have taken a look at the code, it is evident that once we have used the KeyDown method, the Shift key was pressed down. So the text ‘eiffel tower’ that was fed in the next line would have gotten capitalized. Now that the KeyDown has solved its purpose in this scenario, we have used to KeyUp method to release it.

9. MoveByOffset(int xOffSet, int yOffSet)

As seen above, ByOffset(int x, int y) is used when we need to click on any particular location. We can do this by assigning locations for the x and y axes. Now let’s explore the code that we have used for execution.

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;
public class MoveByOffSet {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.sendKeys(eleInput, "Eiffel").build().perform();
        actions.sendKeys(Keys.ENTER).build().perform();
        Thread.sleep(2000);
        actions.moveByOffset(650, 300).contextClick().build().perform();
        driver.close();
    }
}

10. ClickAndHold(WebElement element)

The action method that we will be seeing now in our Action Class Guide can be used when an element has to be clicked and held for a certain period of time.

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.interactions.Actions;
public class ClickAndHold {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.sendKeys(eleInput, "Flower").build().perform();
        actions.moveByOffset(500,300).click().build().perform();
        Thread.sleep(2000);
        WebElement BtnSearch = driver.findElement(By.xpath("//div[@class='FPdoLc lJ9FBc']//input[@name='btnK']"));
        actions.clickAndHold(BtnSearch).build().perform();
        driver.close();
    }
}

In the above code, we have first opened Google and then searched using ‘Flower’ as the input and then performed a left-click action at the defined location. After which, we have performed a click and hold action on the search button.

Note:

In addition to that, if we need the click to be released, we can use the release method to release the clicked element before using ‘build’.

actions.clickAndHold(BtnSearch).release().build().perform();

Uploading a File Using SendKeys Method:

We know that the SendKeys action method can be used to send a character sequence. But one interesting way to use it would be to upload a normal document. If you’re wondering how that is possible, let’s take a look at the code,

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUpload {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://www.leafground.com/");
        driver.manage().window().maximize();
        driver.findElement(By.xpath(" //img[@alt='contextClick']")).click();
        WebElement eleSendFile = driver.findElement(By.cssSelector("input[name='filename']"));
        eleSendFile.sendKeys("C:\\Users\\OneDrive\\Desktop\\Sample.txt");
        Thread.sleep(2000);
        driver.close();
    }
}

In the above code, we have used the SendKeys action method to enter the file’s address path to locate the object that has to be uploaded. The document which we have used here is an input type document as this type of document is only ideal for sending the document using SendKeys.

Note:

Just in case you are not using Google Chrome and would like to execute these action class methods in Mozilla Firefox, all you have to do is just add the driver and set the system property for the gecko driver and initialize the driver object for it using the below line.

System.setProperty("webdriver.gecko.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\geckodriver.exe");
driver = new FirefoxDriver();

Conclusion:

We hope you have enjoyed reading our introductory action class guide that has covered the basic action class methods starting from a basic ‘Click’ to uploading a file using ‘SendKeys’. Action class helps one to perform all the basic actions on a webapp.Release() method, which can be used to release any element that was clicked or held. ‘Perform’ can be used alone, but if there are more composite actions, build and perform should be used together. As a leading test automation company, we are well aware of how resourceful action classes can be when used effectively. Once you have understood the basics, you would be able to perform so many more actions by using combinations of the action methods established in this blog.

A Wall-to-Wall Postman Guide for API Testing

A Wall-to-Wall Postman Guide for API Testing

Postman is an API (Application Programming Interface) development tool that allows users to perform GET, POST, PUT, DELETE, and many other requests to the web service API. Postman allows you to manually test your APIs in both its desktop and web-based applications. However, it also has the ability to automate these tests by writing JavaScript assertions on your API endpoints. As one of the best QA companies, we always thrive on using the best tools for our projects, and Postman has become one of our go-to tools when it comes to API testing. So in this Postman Guide, we will be exploring how to perform the above said requests like Post, Request, and so on. But before we proceed further, let’s have a brief introduction to API testing.

What is API Testing?

API testing is a type of software testing where application programming interfaces (APIs) are tested to determine if they meet the expected functionality, reliability, performance, and security levels. It only concentrates on the business logic layer of the software architecture.

API Testing - Postman Guide

Some of the important components in Postman

  • Pre-Request Script:

Users will be able to write a script to manipulate the data being sent with the request. The pre-request script will run before the request is sent.

  • Tests:

This is the test editor where the users can configure the test cases that are being validated once the request has been fulfilled.

  • Environment:

The environment in postman is a set of key-value pairs which is used to set dynamic values.

  • Collections:

A group of requests will be displayed under collections, and it can be used to organize and keep track of related requests.

Postman Guide to create & run the First API Request:

First and foremost, we have to create a new workspace and click on the New option under ‘File’, and then select ‘Request’.

Creating API request and running in Postman Guide

Enter the name as ‘GET Request’ and then click on + NEW COLLECTION. Following which we will be able to assign a suitable name for the collection.

Once we click on Save, the collection name will be displayed with your API in it. Now that we have prepped everything, let’s make the first API call by following the below steps,

We have to enter the URL in the address bar and click on the ‘Send’ button to see the response.

The response will include details such as the status code, time, size, headers, and cookies alongside the Body.

Response Image

Status Code

So if you take a look at the above image, the HTTP status code is shown to be “200 OK”, which means that everything has worked as expected and that our request is successful.

Time

Right beside the status code, we can see that the time taken to complete the request is 509 ms.

Size

The other available parameter is the size of the requested data, we can see that size is mentioned to be 1.92 KB in the above image.

Note:If we hover the mouse over the time and response values, we will be able to view more details

To save this response, we can simply click on the ‘Save Response’ option.

As stated above, we can also see the body, which is an HTML file in the image. Clicking on the ‘Preview’ option under the body will enable us to view the body in HTML format.

We can click on ‘Cookies’ to view the session-related information and on ‘Headers’ to view other details such as date, content type details, etc.

So by following the above instructions, we have successfully made our first request! Now let’s find out how to send a post request in Postman.

Postman Guide to send a Post Request:

Post is one of the HTTP methods that can be used to add new resources like a webpage and so on. So if we want to create and add a new user to the database, we can utilize the Post request. Likewise, we can also use Post requests for form submissions, authentication requests, and so on.

Let’s see how Post request works:

In Postman, we have an endpoint that responds back whenever we send a request. So, now we are going to send a particular key-value pair in the JSON format to a server.

First, we have to set the HTTP Method to POST.

Next, we have to mention the URL in the address bar.

In the Body tab of the request editor, we should select the ‘Raw’ option and then select JSON from the dropdown list.

We have chosen Raw with JSON as it is one of the most commonly used Post Requests.

So enter the REQUEST in the Body and click on ‘Send’.

Post Request working - Postman Guide

We can see that the user has been created in the above image. In addition to that, we also have the same type of information that we saw earlier that includes status code, time, and so on.

But this time around, we have the status code displayed as 201, which implies that the request has been created.
Click on ‘Save’ to save this request.

‘POST REQUEST’ can be used to add a set of data into the server database. But it is crucial to make sure that the fields are filled with the correct data type, as any incorrect data will result in a 400 Bad Request.

Postman Guide to send a DELETE Request:

Previously, we saw how to send a post request in which we created a user and sent a body. Now let’s see how we can delete a request in Postman. We can use the DELETE HTTP Method to delete an existing record of a user in a database. The expected response in the Status for this is 204.

So primarily, we would have to set the HTTP Method to DELETE, then mention the URL in the address bar, and also mention the final endpoint.

Once the above actions have been completed, we can go ahead and click on ‘Send’.

Expected Report

So as expected, we have the Status Code shown as 204, which denotes that the particular resource has been deleted.

But what if the user has some additional parameters? We can pass query parameters and add them to the body section for deleting those resources as well.

Collections

Collections are nothing but a group of requests grouped into a folder. The simplest example of this would be the way we organize the files on our computers or mobile phones. Let’s say we have multiple files of different formats like text files, audio files, video files, etc. We most probably would create new folders and segregate all the files based on their format.

In the same way, we can create different groups using POSTMAN, and each group can have its own type of request. In addition to having the option to create a collection, we will also be able to share this collection with the team members and encourage healthy collaboration. The other advantage is that since we can share the collection, we will also be able to perform various actions like assigning roles, documentation, mock servers, monitors, etc.

Postman Guide to create a collection:

Now that we have seen the purpose of collection, let’s find out how to create one by making use of the following steps.

Click on the ‘New‘ option, then click on ‘Collection’, and enter the Collection Name. We will be able to click on ‘Create’ once we have also added the description of the collection.

How to create a collection - Postman Guide

Now we can see that we have several options like Run, Share, and so on displayed.

Here we can click on ‘Add Requests’, or replace any existing requests.

Once we click on ‘Run’, a new window will be opened, enabling us to run the collection by clicking on ‘Run My Collection’.

So now we are able to see results for all the requests under the collection, making it evident that we can save an ample amount of time by running multiple requests at a time.

Results of Collection reports

We can click on the ‘Run Again’ option to rerun the collection. Following this, we can click on ‘Export Results’ to export the results as a JSON file. If you take a look at the below image, we can understand that it can be downloaded as well.

Exporting Results in Postman Guide

Different features of collections

• We can add the collections to favorites.

• It helps users share & assign the roles, create fork & pull requests, and also merge changes.

• We can create a duplicate of collections and export them.

Environment in Postman

It is very important to create distinct environments where one is dedicated for testing, one for development, and another for production. An environment is nothing but a set of variables or key-value pairs which we can be used in our requests. We can also change the value of the variables to pass the data between requests and tests. But how we do create an Environment? Let’s find out.

Postman Guide to create an Environment:

1. First, we have to click on the ‘Environments’ option.

2. Then we have to click on the ‘Add’ icon.

3. We can now enter the Environment name.

4. Followed by which we can enter the variable name to use it with the request.

The initial value is shared with your team when you share the variable in a collection as it will be shared with the collaborators who have access to the environment.

How to create an environment

The current value is always used when a request is sent as they are never synced to Postman’s servers. If left untouched, the current value will automatically be assumed as the initial value.

Click on ‘Add’ to create the environment. Once the environment has been created, users can share, copy or even download them if needed.

Global variables in Postman

Global variables allow users to access data between collections, requests, test scripts, and environments. Global variables are not dependent on any environment, making them available for all the requests. They are available throughout the workspace. But on contrary, local variables are available only in particular environments.

When to use Global and Local Variables

When we have multiple key-value pairs which do not depend on any environment, we can make them a Global variable.

Local variables can be used when we have key-value pairs which will change or differ between the environments.

Conclusion:

We hope you have enjoyed reading our Postman Guide for API Testing, as Postman is an effective tool when it comes to API testing. We have just seen the tip of the iceberg here, as these are the most important and basic functionalities every tester must know. As a leading test automation company, we have used Postman in various projects and have always been pleased with its performance. So one can always explore the many more useful functionalities that Postman has to enhance their API testing skills.

A Step-by-Step Jenkins Integration with Selenium Guide

A Step-by-Step Jenkins Integration with Selenium Guide

Jenkins has become the go-to solution for integrating Selenium with Maven as Jenkins enables quicker deployment and more efficient monitoring. The adoption of the CI/CD pipeline has become more prevalent in the software arena. In addition to being a resourceful DevOps tool, Jenkins is also very effective when it comes to building the CI/CD pipeline. As one of the best QA companies, we have used Jenkins as it helps to check the latest build that can be deployed to the production environment. It also makes the process of Selenium test automation much easier with the help of Maven. So in this Jenkins integration with Selenium guide, we will be going through the step-by-step process on how to do it. Before we proceed further, let’s take a look at a few basics.

An Introduction to Selenium and Jenkins:

Selenium is an open-source automation tool that is widely used for testing web applications across various browsers like Chrome, Mozilla, Firefox, & Safari. Selenium will be able to automate these browsers using Selenium WebDriver. Test scripts can be written in any programming language like Ruby, Java, NodeJS, PHP, Perl, Python, etc.

As stated earlier, we all know Jenkins is an open-source automation tool that allows continuous integration (CI) and continuous delivery (CD) and that it is a java based application. Jenkins is mainly used to build and test any software project, making it easy for developers to continuously work and integrate changes to the project.

Installation of Selenium and Jenkins

Before heading over to the Jenkins integration with Selenium, let’s take a look at how to install and set up both Jenkins and Selenium.

Steps to Download Jenkins

1. Download Jenkins from their official website.

2. Unzip the file and open the Jenkins exe file.

3. Click ‘Next’ to start the installation.

Jenkins Integration with Selenium Setup

Jenkins Integration Destination Folder

Port Selection in Jenkins Integration

Installation of Jenkins

Java Home Directory - Setup

Setup Completion of Jenkins Integration with Selenium

4. Click the Finish button to complete the installation process.

5. You will be redirected automatically to a local Jenkins page, and the port number would be 8080 by default. We can also launch a browser and navigate to the mentioned URL http://localhost:8080

Creating an admin account to access Jenkins

1. You can obtain and enter the secret password by navigating to the mentioned path as shown in the below image. Once you have entered the password, click on Continue.

To Unlock Jenkins Integration with Selenium

2. After entering the secret password, you will be asked to install plugins. Click on the required plugins option so that the recommended plugins could be downloaded and installed.

To Customize Jenkins Integration with Selenium

3. After the successful installation, you will be asked to create an administrator account with the following details that are mentioned in the screenshot.

Creating Admin User

4. Once you have successfully installed Jenkins, the default Jenkins dashboard can be seen as shown below.

Jenkins Integration with Selenium Dashboard

Jenkins integration with Selenium

The Jenkins integration with Selenium can be achieved in various ways and we will be focusing on how it can be established using Maven in this guide. Let us quickly introduce what is Maven, why we have chosen Maven, and go through the installation process as well.

What Is Maven?

Maven is a software project management & build management tool which allows us to add and manage all the dependencies in a single pom.xml file.

Why Maven for Jenkins integration with Selenium?

1. It can act as the central repository to get dependencies

2. Maven helps to maintain a common structure across the organization

3. It makes integration with CI tools easier.

How to Install Maven?

1. Download Maven from their official site.

2. Then add MAVEN_HOME under system variables as shown below

Install Maven in Jenkins Integration

3. Now, set up the path for the bin directory of the maven directory.

Maven Setup

4. To verify if maven has been installed successfully, type the following command in the command prompt.

mvn --v

Maven Installing Checking

5. Post the verification, you can go ahead and create a maven project and add the maven dependencies in the pom.xml file that will be used to achieve Jenkins Integration with Selenium.

POM.xml file

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>MyfirstDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.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.22.1</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>E:\MyfirstDemo\testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Using the Java class ‘Sample.java’, we create a WebDriver script. Jenkins Integration with Selenium

package Demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Sample {
    @Test
  public void demo() {
    System.setProperty("webdriver.chrome.driver","src/Drivers/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.cricbuzz.com/");
    String baseTitle = driver.getTitle();
    System.out.println("title =" + baseTitle);
    driver.manage().window().maximize();
    }
}
TestNG.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite">
<test name="demo">
    <classes>
        <class name="Demo.Sample">
        </class>
    </classes>
</test>
</suite>

How To Integrate Selenium Tests In Maven With Jenkins?

So the next aspect that we are going to cover in this Jenkins Integration with Selenium guide is to see how to integrate Jenkins with Selenium WebDriver and how Maven is instrumental in the integration of Jenkins with Selenium test scripts. For a crystal clear understanding, we have also added screenshots of all the important steps.

Start the Jenkins server and launch the browser and navigate to the localhost using the mentioned URL http://localhost:8080.

Steps:

1. The first and foremost step would be to create a new project by choosing the ‘New Item’ option from the Jenkins dashboard.

New Project in Jenkins

2. Obviously, the next step would be to give the new project that we have created a name. In this case, we have used “DemoProject” as the name of the project for explanation purposes. It goes without saying that you can name the project as per your wish. Once the name has been entered, we have to select ‘Maven project’ as the option from the given list and then click on OK.

Project Creation

3. The created project file can be seen in the Jenkins dashboard, and so we would have to select the project from the list to proceed further.

Dashboard

4. From the many options that appear on the left, click on ‘Configure’.

Configuration

5. Automatically Jenkins takes us to the project configuration view where we can configure the project-related details under the General tab. As shown in the image, this section includes the name and description of the project.

Project Configuration

6. The next section is the Source Code Management, under which we have to select the ‘None’ option.

The Git Option:

Here, we select ‘None’ in the Source Code Management section as we just need a build.
If you select Git, you would need to commit to the repository and enter the credentials by clicking on ‘Add’. In this Jenkins Integration with Selenium guide, we will be only focusing on the aspects and features needed to make the integration possible.

Source Code Management

7. So we can head straight to the Build section next, and it would require two important steps to load the POM.xml file. Under the Root POM, you have to enter the complete path of the pom.xml that you have created. Under the Goals and options, you would have to enter the following command

clean test

Jenkins Integration with Selenium Build Section

8. Once these crucial pieces of information have been filled in, we can scroll down and click on ‘Apply’ and then finally ‘Save’.

9. Once the above step is completed, we head back to the project where we have to click the ‘Build Now’ option.

Build Now

10. Now that we have manually triggered the build in Jenkins, the job will run after the completion of the build.

Status of the Build

Console output

11. The results can be viewed in the console output as shown below.

Jenkins Integration with Selenium Console Output

Conclusion:

We hope this step-by-step Jenkins integration with Selenium has been helpful to you. Using this integration, we have been able to build and test our software projects efficiently and achieve the goal of continuous integration. Using Jenkins, we have been able to provide the best Selenium testing services to our clients. Beyond the benefits that we have already seen, Jenkins allows us to schedule jobs to run at any time, and it also supports a wide range of selenium plugins that will come in handy to achieve a variety of project needs.

The Agile Testing Best Practices that will increase your Productivity

The Agile Testing Best Practices that will increase your Productivity

Testing is essential to produce quality software. Agile approaches aim to integrate quality assurance into product development from the ground level up by having techies heavily involved with testing right from the initial stages. The idea behind this process is that if problems can be identified and corrected earlier in the design process, then the companies will be able to create defect-free products at quicker rates. Most of the agile teams are flying blind without having any proper strategies or measurements to follow. But as one of the best software testing service providers, we have been able to put the agile approach to good effect. So in this Agile Testing Best Practices blog, we will be sharing some important aspects that will help improve your performance in agile testing.

In addition to that, we will also be focusing on the inherent challenges and the many advantages that the agile method brings to the table.

How Agile testing is different from traditional testing:

Agile testing is a core part of the agile software development process. It is also very different from the conventional testing methods. Traditional testing is done in a phased manner so that the end-product doesn’t get released until all the defects have been fixed. But on the contrary, agile testing follows an iterative approach. So defects are fixed in each sprint and released right away. Testers define the success or failure of the team’s attempts to be agile as they are a part of the delivery team, making them an integral part of any agile team. So the adaptability of testers in SDLC is very important in the agile approach.

Five things make agile testing different from traditional testing, and they are

  • Continuous Involvement
  • Essential Tools
  • Multidimensional Skills
  • Effective Communication
  • Quick Feedback from Testing

 

Agile Testing life cycle:

1. User Story Analysis,

It is important to understand the release plan and plan the user stories across the sprints in a release.

2. Test plan / Estimate,

It gives the ability to have all the high-level scenarios, requirements, and estimates in one plan. It is created for each release, and it should also be updated for every release.

3. Sprint Planning,

The purpose of sprint planning is to define what should be delivered in a sprint and how that can that be made possible. The team assembles together to achieve the required velocity of the sprint.

4. Environment Setup,

Agile is a process that requires consistent teamwork and the work environment plays a huge factor in encouraging the team to work towards a common goal. So nurturing such an environment is one of the vital agile testing best practices that can make a difference. This can be accomplished by valuing each individual & their ideas and by healthy collaboration as the process demands frequent changes.

5. Implementation and Execution,

The creation of test cases across the assigned user stories and peer review is performed in this stage. For better quality deliverables, developers can take a look at these test cases and ensure that the overall scenarios have been enlisted. The distribution of various tests based on risk analysis is vital. So test cases must comprise of all test types like Functional, UI, Usability, cross-browser, etc. So once the test cases have been created, we have to ensure if the stories are ready for testing and execute the created test cases.

6. Defect Reporting,

The ultimate point of any form of software testing is to identify the bugs and report them so that they can be fixed. So it is important to devise an efficient method to report all the encountered bugs in an effective bug management tool. Healthy real-time collaboration with the developers can be achieved only when the defect log contains information like summary, description, priority, date of identification, steps to reproduce, name of the tester, unique identifier, etc. Such an in-depth report will enable us to conduct a triage meeting to plan and fix the bugs that have been logged.

7. Release Activity,

Once we are past all the above stages, the build can be deployed for UAT where testing can be performed with a few users. If the build clears the smoke tests that will be performed by the alpha testers, then the release can be given to the beta testers who will test the build before signing it off from their end and ship it to production.

8. Getting ready for the next release,

After the release, the team should prepare for their next release. Any and all business clarifications or issues should be raised and cleared during this phase.

 

The Quadrants for Agile Testing Best Practices

Agile testing can be simplified by using a system of quadrants that provides necessary classifications that determine which type of test should be run, how often it should be run when it should be run, and who it should be run by. Since there are so many types of testing like acceptance testing, regression testing, unit testing, and so on. Quadrants help reduce the difficulty in deciding which test has to be used where. It will also answer the question of whether manual or automated testing is better suited for the current iteration of the product.

So, now let’s find out how quadrants work their magic. Quadrants divide the whole testing methodology into four grids. These 4 grids help the whole team to communicate and deliver the quality product on time.

Quadrants of Agile Testing

Quadrant Q1 – The tests in the first quadrant are unit level, technology facing, and also supportive to the developers. Unit tests and other component level tests that test the code belong to this quadrant. In general, the tests in this quadrant are automated.

Quadrant Q2 – The second quadrant consists of tests that are system level, business-facing, and help conform product behavior. Functional tests belong to this quadrant. These tests can either be manual or automated.

Quadrant Q3 – The tests in this quadrant are system or user acceptance level, business-facing, and focused on real-time scenarios. User Acceptance Tests belong to this quadrant. These tests are manual.

Quadrant Q4 – The tests in the final quadrant are system or operational acceptance level, technology facing, and focus on performance, load, stress, maintainability, and scalability. Special tools can be used for these tests, along with automation testing.

 

Agile Testing Best Practices to Overcome Challenges:

Let’s take a look at some of the most common challenges that agile teams will face during testing and see how we will be able to overcome them as well.

Last-minute changes:

Changing requirements is an inherited challenge of the agile methodology. This means that even if a work is already completed or half done, it might have to go through some modifications or worst-case scenario, get scrapped as well. So this will most definitely will have an unexpected change in the scope of testing.

How to master?

Testers must be ready to react to the changes or modify the processes in agile methodology as the process is itself prone to changes. Whenever there is a change in the requirements, testers should share the information of what tests they have actioned and which part of the application they have not yet tested. This can help the team understand how to make the required changes.

Not Enough Information (one-line stories):

Sometimes product owners will just have an idea of what features are required. So business owners may not even be aware of the specific requirements. In such situations, testers will not have a good set of details about the user stories at their disposal. All they might have could be just single-line information which is insufficient to build comprehensive test cases. This causes a significant amount of hindrance to the testers.

How to master?

In this situation, the testers can collect all the minutes of each requirement before they start testing and they can even come up with high-level scenarios for the stories and confirm them with the author or product owner and then approach the test cases.

Lack of Communication:

Without effective communication between developers, testers, and the product owner no process can work. So effective communication is also one of the most important agile testing best practices. Lack of communication can result in different teams flying blind with no proper goal as to what should be accomplished.

How to master?

Daily standup meetings with the team are strongly encouraged. It is also important to make sure that the meetings are not too long. Daily standups help identify roadblocks and solve them on a day-to-day basis. It also helps to keep the developers and product owners on the same page as the rest of the team.

Frequent regression testing:

As features get pushed by developers continuously, testers would have to run regression tests very frequently as the chances of the new features breaking the previous code are much higher. The other major challenge is that testers would have to test the application’s functionality correctly for all the users. Testers would also have to check the application’s behavior on different devices.

How to master?

Automation skills can be a great help for this situation in agile projects. Automating the regression test can save you a lot of time, and Selenium is the most popular browser automation tool that might solve all your needs. Apart from that, testers can use tools like Docker or VisGrid to run their automated test scripts in parallel across various browsers and devices.

Technical Skills:

As software becomes more mature, the complexity increases along with it as well. Testers should be in a position to help developers with API testing, integration testing, and more. So having strong technical skills is one of the basic requisites of a tester who is working in agile.

How to master?

Being in the process of continuous learning always helps people excel in their respective fields. Likewise, testers can learn programming languages like Java, Python, C#, etc., and learn automated testing tools like Selenium, JMeter, and so on. It is also crucial for the team to comprise dedicated testers with professional experience. If you are looking for the best agile testing tools, then you could read our blog and explore your options.

 

Conclusion:

We hope you have enjoyed reading this blog and that it has been informative as well. These agile testing best practices have helped us deliver the best software testing services to our clients, and hope it will enhance your testing methods as well. Obviously, these tips alone will not equip you to face any challenge that comes your way. But these general tips will definitely help you overcome the regular challenges and also help you find the right solutions for every new challenge you would face.

TestNG Tutorial : An Introduction to its Attributes and Features

TestNG Tutorial : An Introduction to its Attributes and Features

TestNG is not the only option available in the market. But most of the automation testers prefer TestNG over other options like JUnit because TestNG allows parallel execution of test cases that saves loads of time possible with the help of the ‘parallel’ keyword in the XML file, TestNG’s seamless integration with tools like Jenkins, Maven, etc., and grouping of test cases also becomes easy with the use TestNG. These features have been instrumental in us providing the best software testing services to our clients. So in this TestNG tutorial, we will be focusing on how to make use of all these advantages and also explore all the advantages that TestNG brings to the table.

TestNG is an open-source testing framework where NG stands for Next Generation. It provides many features to execute the test methods by using various annotations like @Test @BeforeTest, @BeforeClass, etc. TestNG allows its users to generate robust test results that include the number of test cases that have Run, Passed, Failed, and Skipped. It can also be used to implement the logging feature using TestNG Listeners. On the whole, TestNG can also be used across various testing types like Unit, Regression, Functional, and API Testing. But before we get started with the TestNG Tutorial, let’s see how to set it up.

Installation and Setup of TestNG in IntelliJ:

IntelliJ requires a JAR file to add dependencies for TestNG script development and for running the test suites. So if it is a Maven Project, we would have to download the TestNG Jar File. Since we will be running tests on Java, we need to download an external TestNG Jar File onto our system by using the provided link.

Direct download link: TestNG/7.4.0/testng-7.4.0.jar

Reference: org.testng/TestNG

Please refer to the below image and instructions for a step-by-step guide,

Step by Step Guide

i. Open IntelliJ,

ii. Create a new JAVA Project,

iii. Navigate to ‘File’ >> ‘Project Structure’ in IntelliJ,

iv. Click on ‘Libraries’ from Project Setting,

v. Add it to your ‘TestNG’ jar file, and then click on the ‘Apply and OK’ button.

Selecting Library Files

If we want to work on a maven project, we have to mention the dependency in the POM.xml file

Maven Repository

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.4.0</version>
    <scope>test</scope>
</dependency>

TestNG Annotations:

TestNG annotations that are used to execute the test scripts can be defined by ‘@Test’ annotations. Before we head over to other aspects of the TestNG Tutorial, let’s take a look at the various annotations that are available in TestNG along with a short description of them.

Types of TestNG Annotations:

TestNG Annotation Order

@Test Annotations:

We use this annotation to mark a method as a test method. The methods marked with @Test annotation are automatically invoked by the TestNG engine in default order (i.e.) alphabetically.

Syntax:

@Test
public void TestMethod1() {
System.out.println("\n Test-Method-001");
}

So in this part of the TestNG Tutorial, we will be focusing on the most important attributes of @Test annotations, starting with the description

1. ‘Description’ attribute of @Test Annotation:

The ‘Description’ keyword is used to provide a description of the test case. It can also be termed as a one-line summary, and it has been illustrated in the below example that describes the action of the user in a single line.

@Test(description = "User visits Codoid Home page")
public void launchCodoidURL(){
System.out.println("\n >>> User visits Codoid Home page...");
}
2. Test Methods with Priority:

As mentioned earlier, we are aware that the methods will execute multiple test annotations alphabetically by default. But what if there is a need to run the methods or the test annotations based on defined priorities? Here is where the ‘Priority’ attribute comes into play, as it can be used to assign priorities to each test method. The highest priority would be given when a test method is marked with 1 and the priority decreases inversely as the number increases.

We have mentioned syntax below to denote how the priority attribute would function.

Syntax:

@Test(priority = 1)
public void Test1() {
System.out.println("\n Test-1");
}

@Test(priority = 2)
public void Test2() {
System.out.println("\n Test-2");
}
3. Test Methods with Priority & without priority:

So in the above-mentioned syntax code, we saw 2 sets of programs that had defined priorities. But what if there is a need to define priorities only for a certain number of methods? It is very easy to accomplish as you can simply leave the methods that don’t need defined priorities and mark the other methods alone in the order that you wish. It is worth noting that the methods that had no defined priority will be run first on an alphabetical basis and then followed by the defined order.

Syntax:

@Test(priority = 1)		//with Priority
public void Test1() {
System.out.println("\n Test-1");
}

@Test		//without priority
public void TestMethod1() {
System.out.println("\n Test-Method-001");
}

@Test		//without priority
public void TestMethod2() {
System.out.println("\n Test-Method-001");
}

@Test(priority = 2)		//with Priority
public void Test2() {
System.out.println("\n Test-2");
}

Code Explanation:

– Non-Prioritized methods ‘TestMethod1() and TestMethod2()’ have been executed in alphabetical order. (Line No: 60 and 65)

– Prioritized methods ‘Test1() and Test2()’ have been executed based on the priority level. (Line No: 55 and 69)

4. Depends On Methods in TestNG:

In our test scripts, we might have some methods that depend on the execution of another method before it is executed. For example, if a user wishes to send an email using the email application, then the user has to be logged in to the application first. So there will be no point in trying to send the mail if the sign-in is incomplete. So we can make use of this attribute that will help methods from getting executed if their dependent method doesn’t get a ‘Pass’. The same scenario is shown below as an example.

Syntax:

@Test
public void UserLoginIntoEmailApplication(){
    System.out.println("\n >> User Login :: ");
}
@Test(dependsOnMethods = "UserLoginIntoEmailApplication")
public void UserSendAnNewEmail(){
    System.out.println(">> User send an eMail");
}

Depends on Methods

Sometimes, there might be scenarios where a test case depends on more than one test method. So we can pass the parameters in annotations as shown below.

Syntax for dependsOnMethods: (Multiple Dependent Test methods)

@Test(dependsOnMethods = { "UserLoginIntoEmailApplication", "UserSendAnNewEmail" })
public void SignOut() {
System.out.println(">>> Sign Out");
}

Syntax for depends on Methods in TestNG

5. TestNG Groups:

The grouping concept is one of the best features of TestNG and one of the important parts of this TestNG Tutorial. So using this concept we can create a group of test methods based on modules/test cases. For example, the client requirement might demand you to execute a large number of smoke or regression tests. So you can simply pass the parameter in group attributes as shown below.

Syntax:

@Test(groups = { "Regression" })
public void userLogin() {
....
}
@Test(groups = { "Regression" })
public void userSendEmail() {
....
}

So the groups are specified in the ‘.xml’ file and can either be used with the “groups” tag name or under the ‘test’ tag.

Syntax:

<groups>
<run>
<include name = "Regression"></include>
</run>
</groups>

TestNG Groups

DataProvider in TestNG:

In this method, a user will be able to pass the test data in test methods and also iterate the test methods using different data from the @DataProvider annotation, and it will return the 2D array objects.
Let’s see a simple example for this annotation,

Code:

@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod() {
return new Object[][]{{"Codoid-001"}, {"Codoid-002"}};
}
@Test(dataProvider = "data-provider")
public void testDataProviderConcept(String strData) {
System.out.println("\n >> Data: " + strData);
}

Code Explanation:

We have maintained the array object and Test methods in the same class. In this method, the “testDataProviderConcept(String strData)” will iterate based on the array size. It will also retrieve the values “Codoid-001 and Codoid-002” from the ‘dataProviderMethod()’ with the help of the @DataProvider annotation.

Data Provider in TestNG

Multiple Parameters in TestNG DataProvider:

It is even possible to pass multiple data through a single parameter. In this test method, we will be able to retrieve the data using multiple arguments as shown in the example,

For example,

@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod(){
return new Object[][] {{123,456 ,789}, {001, 002, 003}};
}
@Test(dataProvider = "data-provider")
public void testMethod(int value1, int value2, int value3) {
System.out.println("\n >> value1: "+value1+"; Value2: "+value2+"; Value3: "+value3);
} 

Multiple Parameters in TestNG provider

DataProvider In TestNG Using Inheritance concept:

If you are looking for a way to maintain the code based on the project structure, then the DataProvider methods can maintain one class and the test methods can maintain another class. Let’s take a look at the example to find out how.

For example, we can access the dataprovider class using another attribute like “dataProviderClass”

Syntax :

@Test(dataProvider = “data-provider”, dataProviderClass = DP.class)

Note:

i. dataProviderClass // attribute Name

ii. DP.class // class Name; To inherit the other class.

Code:

//Class-1
@Test(dataProvider = "data-provider", dataProviderClass = DataProviderUtil.class)
public void testDataProviderConcept(String strData) {
System.out.println("\n >> Data: " + strData);
}
//Class-2  "Class Name: DataProviderUtil"
@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod() {
return new Object[][]{{"Codoid-001"}, {"Codoid-002"}};

TestNG Tutorial for using Excel Workbook as a Data Provider:

Now that we have seen how to pass the parameter with single or multiple data through an array object, but what if there is a need that demands a large number of data be used? Adding everything to the code will not be an optimal choice at all. We have a solution to overcome this in our TestNG Tutorial and so let’s focus on how we can retrieve data from an Excel workbook. Knowing this will come in very handy while executing Functional tests, and when there is a need to create a large amount of test data for performing Load tests.

We are going to implement the Excel workbook in the TestNG-DataProvider annotation to fetch the data from the excel sheet and search the products in Amazon. In the example, we have listed a few mobile phones like iPhone 12, Pixel 4a, and so on in the excel sheet.

The below-mentioned Excel util class is used to retrieve the data from the Excel sheet.

ExcelUtil.JAVA

Code:


/*Description: We can retrieve the data from the Excel workbook
    * parameter-1: Excel workbook directory path,
    * parameter-2: Sheet name*/
    public static Iterator<Object[]> getTestData(String strWorkbookPath, String strWorksheetName) {
        List<Object[]> data = new ArrayList<Object[]>();
        int inRowCounter = 0;
        try {
            FileInputStream file = new FileInputStream(new File(strWorkbookPath));
            //Get the workbook instance for the xlsx file.
            HSSFWorkbook workbook = new HSSFWorkbook(file);
            //Get the first sheet from the workbook
            HSSFSheet sheet = workbook.getSheet(strWorksheetName);
            //Get an iterator to all the rows in the current sheet
            Iterator<Row> rowIterator = sheet.rowIterator();
            Row firstRow = rowIterator.next();
            Map<String, String> columnNamesMap = getColumnNames(firstRow);
            while (rowIterator.hasNext()) {
                Iterator<Cell> cellIterator = rowIterator.next().cellIterator();
                Map<String, String> rowMap = new LinkedHashMap();
                for (Entry entry : columnNamesMap.entrySet()) {
                    String strColumnName = entry.getKey().toString();
                    String strValue = cellIterator.next().toString();
                    rowMap.put(strColumnName, strValue);
                }
            }
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data.iterator();
    }

    private static Map<String, String> getColumnNames(Row row) {
        Map<String, String> columnNamesMap = new LinkedHashMap();
        Iterator<Cell> cells = row.cellIterator();
        while (cells.hasNext()) {
            String strColumnName = cells.next().toString();
            columnNamesMap.put(strColumnName, strColumnName);
        }
        return columnNamesMap;
    }
DataProvider.Class
@DataProvider(name = "AmazonProduct", parallel = false)
        public static Iterator<Object[]> getDeviceName() {
            String strWorkBookPath = new StringBuilder().append(System.getProperty("user.dir")).append(File.separator)
                    .append("resources\\testdata").append(File.separator).append("testdata").append(".xlsx").toString();

            Iterator<Object[]> testData = ExcelUtil.getTestData(strWorkBookPath, "Mobiles");
            return testData;
        }
TestScripts.java
@Test(dataProvider = "AmazonProduct", dataProviderClass = DataProviderUtil.staticProviderClass.class)
public void searchAmazonProducts(Map<String, String> dataMap) {
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.amazon.in/");
        wait = new WebDriverWait(driver, 25);
        WebElement txtSearchEngine = wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector("#twotabsearchtextbox")));
        System.out.println("\n Devices : " + dataMap.get("Devices"));

        txtSearchEngine.sendKeys(dataMap.get("Devices"));
        txtSearchEngine.submit();
        driver.quit();
    }

Please refer to the below image,

Data provider in Excel Workbook

Parameterization in TestNG:

When there is a need to perform tests by using different test data, or when you are looking to test by logging in with a different user that has distinct usernames and passwords then Parameterization will come in handy as the “@Parameters” annotation in TestNG allows argument values to pass to Test methods via the testng.xml file. (Parameter values are declared in testng.xml) We have explained the different user scenarios using an example.

Syntax:

@Parameters({ “param-name” })

Let’s write a simple program for the @Parameters annotation,

Code:

@Test
@Parameters({"Username"})		
public void TestMethod1(String strUsername) {	
//We can retrieve the data using this argument. (It’ll retrieve from testng.xml file)
System.out.println("\n Username : " + strUsername);
}

Parameterization in TestNG

TestNG Tutorial for Parallel Execution:

Saving time during the testing process is always a priority, and one of the best possible ways to do it would be by executing tests in parallel rather than sequential execution. So as promised at the beginning of this TestNG Tutorial, let’s see how we can have test suites executed in parallel on different browsers, and how it can be even defined in the Testing.xml file.

TestNG provides different levels of execution that we can achieve by using the Testing.xml file. The attributes that we can use to achieve them are,

i. Methods,

ii. Classes, and

iii. Tests.

i. parallel=”methods”:

We had already seen about methods that are dependent on other methods for their execution, so accordingly if you are looking to execute many independent methods in parallel, then this attribute can be used. Using this attribute, all test methods will run on a separate thread. In the below example, we have executed two test methods in two threads.

Note: Thread count is the specified number of browser instances that should be assigned for this test execution.

Syntax:

<suite name="Test-method Suite" parallel="methods" thread-count="2" >

Parallel Methods

Code :

TestParallelForMethodsExecution.java
public class TestParallelForMethodsExecution {

    @Test
    public void visitCodoidPage() {
        String baseUrl = "https://codoid.com/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        WebDriverWait wait = new WebDriverWait(driver, 25);
        String testTitle = "QA Testing Company - Software Testing Services";
        boolean isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
        WebElement elmntAboutUsTab = driver.findElement(By.xpath("//ul[@id='top-menu']/li/a[text()='About Us']"));
        elmntAboutUsTab.click();
        driver.close();
    }

    @Test
    public void visitAmazonPage() {
        String baseUrl = "https://www.amazon.in/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        WebDriverWait wait = new WebDriverWait(driver, 25);
        String testTitle = "Online Shopping site in India";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
        driver.close();
    }
}
TestNG.xml
<suite thread-count="2" name="Parallel-Test-Suite" parallel="methods">
    <test name="To Run TestNG :: Parallel methods concept">
        <classes>
            <class name="scripts.TestParallelForMethodsExecution"/>
        </classes>
    </test>
</suite>
ii. parallel=”tests”:

But the problem is that the above type will not work if we have a lot of test methods that are dependent on each other like how we saw earlier with the email example. So this attribute can be used to overcome this issue by adding all the dependent tests to a suite file (Testing.xml) and executing it separately in a thread as each tag will be considered a test suite and it’ll be executed in a separate thread.

Syntax:

<suite name="Test-Suite" parallel="tests" thread-count="2">

Parallel Test

Code

MultipleSession1.java
public class MultipleSession1 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;

    @Test
    public void visitAmazonPage() {
        String baseUrl = "https://www.amazon.in/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);
        String testTitle = "Online Shopping site in India";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
    }

    @BeforeMethod
    public void beforeMethod() {
        System.out.println("\n Starting Test On Chrome Browser");
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
}
MultipleSession2.java
public class MultipleSession2 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;


    @Test
    public void visitCodoidAboutUsPage() {
        String baseUrl = "https://codoid.com/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);
        String testTitle = "QA Testing Company - Software Testing Services";
        boolean isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
        WebElement elmntAboutUsTab = driver.findElement(By.xpath("//ul[@id='top-menu']/li/a[text()='About Us']"));
        elmntAboutUsTab.click();
    }


    @BeforeMethod
    public void beforeMethod() {
        System.out.println("\n Starting Test On Chrome Browser");
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
}
TestNG.xml
<suite thread-count="2" name="Parallel-Test-Suite" parallel="tests">
    <test name="To Run TestNG :: Parallel Tests concept - 1">
        <classes>
            <class name="scripts.MultipleSession1"/>
        </classes>
    </test>
    <test name="To Run TestNG :: Parallel Tests concept - 2">
        <classes>
            <class name="scripts.MultipleSession2"/>
        </classes>
    </test>
</suite>
iii. parallel=”classes”:

This type has similar usage scope as the previous one with one major difference. Using this attribute, we can execute tests under each class in an individual thread, and the same has been explained in the below example.

Syntax:

<suite thread-count=”2” name =”Parallel-Test-Suite” parallel=”classes”>

Parallel Classes

Code:

Test1.java
public class Test1 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;

    @Test
    public void Test1() {
        String baseUrl = "https://codoid.com/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);
    }

    @Test
    public void Test2() {
        String testTitle = "QA Testing Company - Software Testing Services";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
    }
    @Test
    public void Test3() throws InterruptedException {
        WebElement elmntAboutUsTab = driver.findElement(By.xpath("//ul[@id='top-menu']/li/a[text()='About Us']"));
        elmntAboutUsTab.click();
    }
    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
 }
Test2.java
public class Test2 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;


    @Test(priority = 1)
    public void launchAmazonURL() {
        String baseUrl = "https://www.amazon.in/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");

        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);

    }

    @Test(priority = 2)
    public void verifyAmazonTitle() {
        String testTitle = "Online Shopping site in India";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
    }

    @Test(priority = 3)
    public void navigatesToAboutUsPage() throws InterruptedException {
        WebElement elmntAmazonPayTab = driver.findElement(By.xpath("//a[text()='Amazon Pay']"));
        elmntAmazonPayTab.click();
    }

    @BeforeMethod
    public void beforeMethod() {
        System.out.println("\n Starting Test On Chrome Browser");
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
}
TestNG.xml
<suite thread-count="2" name="Parallel-Test-Suite" parallel="classes">
    <test name="Using Classes attributes for parallel execution.">
        <classes>
            <class name="scripts.Test1"/>
            <class name="scripts.Test2"/>
        </classes>
    </test>
</suite>

In the above 3 points, it can be seen that we have defined the keywords for parallel (classes, tests, and methods) attributes on the Testing.xml file. Now, we’re going to explain the sample scripts for classes and methods.

Conclusion:

As promised at the beginning of this TestNG tutorial, we have explored all the plus points of TestNG. So we hope this information would be useful and that you have enjoyed reading this blog. As one of the leading automation testing companies, we have always found TestNG beneficial in crucial circumstances, and hope it will come in handy for you as well.