11 Tips and Tricks For Appium and Selenium

Selenium and Appium are two well-known automation testing tools. Selenium is largely leveraged for testing web applications whereas Appium is widely used for testing mobile applications. Bundled with many features, both these tools are highly recommended for software testing.
But you need to have a proper understanding of these appium and selenium tools to get best out of them.  There are few tips and tricks that can help you get best out these tools and leverage them to their best abilities.
Let’s make our job easier with these veteran Tips and Tricks about Appium and Selenium.

The Use of Waits: 

Using Thread.Sleep() is a common method of “waiting” while any processing is going on. But it possesses a few drawbacks. Here is how we can overcome it.
a)    WebDriverWait.  It census your query every 500ms, and return when the wait condition is fulfilled. WebDriverWait can explicitly put a maximum threshold to elude locks and infinite waiting.
b)    FindElementBy / FindElement(..): Second method is by invoking FindElementBy or just FindElement(..). FindElementBy waits until the element is found and returns null if maximum wait time passes. But be sure you have to explicitly configure the implicitly waits.
1. Locating Elements
Locating element is not a tough job in selenium and there are many ways to do it. But the haunting part is getting StaleElementReferenceException.
It happens when you assign IWebElement reference but it already has some other location in the DOM. The solution to StaleElementReferenceException is to re-query and reassign the element reference.
2. Sending Keyboard input
Selenium allows sending inputs in two ways. First is by setting “value” property of editable elements by using ExecuteScript() / ExecuteAsyncScript(). Second is to use SendKeys() API.
I would suggest you use ExecuteScript() / ExecuteAsyncScript() method when you are more concerned about filling in a few fields and when you are not concerned about DOM events being fired and concurrent character-by-character verification.
But if you want to focus on real-time validation, the second method i.e. using SendKeys() API will be more apt for you.
3. Executing JavaScript code
You can execute JavaScript in either of the below-given ways depending upon your requirements.
i)    ExecuteScript().ExecuteScript() does not execute the next line of         test code till script execution is returned.
ii)    ExecuteAsyncScript() does not block your test code.
4. Drag & Drop Interfaces
Action Builder API, and the “DragAndDrop” and “DragAndDropToOffset” methods support easy drag and drop interface in Selenium.
5. Switching between windows and iframes
You can easily switch between windows and frames in Selenium.

  1. For iFrames

driver.SwitchTo().Frame(frameElement); //IWebElement

  1. For Windows

driver.SwitchTo().Window(handle);// driver window handle
and then can switch back to the original window by using
driver.SwitchTo().DefaultContent();

  1. Using drivers for multiple browsers

When using the driver API, always refer it by using RemoteWebDriver class for all the browsers used for running tests.
It is good to label your environment in a text/XML file and then deconstruct this and return the correct driver instance.
6. Cleaning UP
When you are done with your testing, you need to free all the resources and close the browser.
For this you can use Close(), Quit(), and Dispose().  Quit() closes all browsers, close() closes the existing browser  while Dispose() calls the quit() and closes all browsers.
Now when we are done with a few tips and tricks of working with selenium, let us now get better in our Apium skills.
Appium is one of the widely used mobile app testing tools. Though its users encounter some common problems while using it…
Here are some tips and tricks that can help you handle some common problems faced in using it and making it’s working more efficient and effective.
So, here we go…
7. Writing cross-platform tests 
One of the major issue in testing mobile apps is we have to write different test scenario for Android and iOS. Having common tests can be a big benefit in terms of saving time and efforts.
Though it gets much easier having the same set of test cases for both if your application is the same from a UI point-of-view.

Read also :  Testcafe Vs Selenium. Which is Better?

Just make sure that the accessibility IDs on corresponding UI elements in each version of the app matches with each other. If it stands true, you can run the same test on both applications. Also, be sure your test sets up the appropriate capabilities for each platform.
Based on different platforms, here are some more and little-known tips and tricks about Appium that can make your testing easier.
8. For All Platforms

  • AutoWebView – it is very useful for Cordova apps and helps to start in the webview context.

9. For Android

  • ignoreUnimportantViews – It is a very useful method to quicken your Android tests.
  • nativeWebScreenshot – Helps you to take a screenshot from UIAutomator. It is very useful if your screenshots from chromedriver are not as expected.

10. For IoS

  • locationServicesAuthorized – It helps you to prevent showing an alert when you are trying to use the user’s location by pre-authorizing location services.
  • Auto[Accept|Dismiss]Alerts – It helps you avoid alerts from disrupting your tests.
  • nativeWebTap – Permits users to use non-javascript taps.
  • safariIgnoreFraudWarning – It is beneficial in cases where your test environment doesn’t have 100% perfect SSL setup.
  • interKeyDelay – Sometimes Appium’s typing speed can cause a problem with your application, in such cases, interKeyDelay can evade the problem.
  • sendKeyStrategy – Helps in avoiding the keyboard altogether.

11. Networking Conditioning
You can use driver.setNetworkConnection(value) to stimulate various states of connectivity when you run your tests.
Hope these tips will prove helpful to you, will be back soon with some more useful testing tips and tricks. So stay tuned!

Why Should You Shift to Functional Automation Testing?

Do you get bored with manually testing your code for bugs again and again? Proper functioning of the code is the foremost thing that matters.  If your code does not act as per the requirement specification, it is no longer of any use.

Functional testing assures that your code functions as per the requirements. But alas! Even a small change or an alteration in your code can alter its working. Hence it is advisable to retest your code every time a change is made to the code.
But running same test cases again and again can be daunting. And there enters automation testing. Automating your functional testing can relieve you of a lot of burdens and can save you a lot of time.
What is Functional Automation Testing? 
Before moving on to functional automation testing, let us first know a little about Functional Testing.
As discussed earlier functional testing confirms that every function of your code works in accordance with the requirement specification. Functional testing requires you to send appropriate inputs and to verify the actual output with the expected output.
But being the foremost quality assurance process, you may be required to repeat functional testing. And hence to ease out your work it is advisable to automate your functional testing process.
Functional Automation testing is a process that assists you in easy and faster execution of your functional test cases. Manual testing requires you to execute the test case step by step, which can be time-consuming as it is done by hand.
And to outcast, this peril, automating functional test case comes as a savior saving on both time and efforts. It helps in executing functional test cases automatically with no human intervention.
Before moving forward let’s look into some drawbacks of manual functional testing.
Drawbacks of Manual Testing
Here are some weaknesses of manual testing that promote testers to adopt automated testing:

  • Manual functional testing is very time-consuming.
  • Functional testing like regression testing becomes very repetitive and losses testers’ interest.
  • It requires many resources.
  • It might miss out on a few scopes of functional testing.

Why Functional Automation Testing?
Considering the current scenario where we develop software at a fast speed and alterations and enhancements are done at an equally fast speed, we need a methodology where we can test our code with an equally high speed. And that is where a need arises for functional automation testing.

Know More: 7 Best Practices You can Consider for Functional Testing

Companies are now moving toward Agile and DevOps, increasing the importance of automation than ever before. The frequent integrations and enhancements in the code require test cases to run quickly and accurately. And automation functional testing assures the best accuracy and quick run avoiding all human errors.
The main reason for a switch to functional automation testing is to save on both time and money. It assists the quick feedback to the developers for any bugs and errors.
Apart from time and money savings, Functional automated testing also benefits in:

  • More precise benchmarking.
  • Fewer faults because of human error.
  • Gives wider test coverage.
  • Assists reusability.
  • Helps in faster release of the software.
  • Assists in faster feedbacks to the developers about the bugs in the code.

So are there any downsides to creating automated tests?
What’s the real story?
Functional test automation as software development
Functional automation tests or any other automation tests are a piece of software code that relies on one or other programing language. This makes it a complete software development activity where you develop a code to test another piece of code.

Developing functional testing code is equally complicated like other software development projects and presenting similar issues like them.
So take care to follow software development best practices to develop a successful functional automation test case.
Should you automate all your test cases?
Automating all the test cases does not seem to be a good idea. Rather, not everything is even automatable. To look out for what test cases you should ideally automate, consider the following things:

  • Deterministic test cases
  • Automate test cases that do not require manual communication
  • Test cases that deals with fiscal-related areas of the software
  • Test cases that deals with risk areas of the software
  • Test that requires running on different data sets.
  • Test cases those are difficult for manual testing.
  • Test cases those are required to run on various browsers, systems, etc.
  • Test cases that is time-consuming.
  • Stress/load test cases
  • Unit test cases

You can consider automating the more time-consuming and repetitive test cases. Though, the criterion may vary depending on various other conditions.
But what about Functional automation testing ROI? Let’s have a look into it.
Functional Automation Testing ROI 
Finally, it is ROI that majorly governs any business decisions. Whether to automate your test cases or not; is also largely dependent on ROI. The determination of ROI for automation testing is tricky. Here is a small formula that can help you find a rough estimate of the automation cost.

Know More: Difference Between Functional and Non Functional Testing

Automation Cost = automation tool cost + cost of the labor to automate test cases + maintenance cost
If your automation test cost turns out to be lower than the manual testing cost, you should look out for automating test cases.  Moreover, testing cost increases with every run in manual testing, whereas the ROI adds up with every run in automation testing
But there are some other factors apart from ROI that can affect your decision to whether or not to automate test cases.
What Not to Automate
Functional automation testing, no doubt save time and efforts. But automating all the test cases is not a good idea. There are certain types of test cases you should not consider automating.

  • Test cases that are to be performed only once.
  • Ad Hoc based test cases.
  • Test cases that do not have a predictive result.
  • Usability test cases.

Be wise in your selection of test cases to automate. Functional test case automation can be highly beneficial for you if done wisely.
Conclusion:
Functional testing is one of the most important phases of STLC. But sometimes functional testing can be very time-consuming and frantic task.

Automating function test cases is one most apt solution to overcome this snag. Functional automation testing can save you both time and money.
So be clever and consider functional automation testing for your upcoming projects.

Selenium Tutorial For Beginners [Step by Step]

Everybody knows about the impeccable selenium! The ultimate tool for testing web applications! for you to learn in detail about how to carry out automation testing, we have written an extensive Selenium tutorial just for you!
This blog comprises of three part,
1. Selenium Tutorial For Beginners
2. Selenium Intermediate Level Tutorial
3. Selenium Advanced level Tutorial

Selenium Tutorial For Beginners

What makes Selenium better?

You don’t need to code anything in Selenium and with this; any beginner will be able to record and play the simplest web application scripts.
Usually, Selenium RC needs a server to be up and running for sending commands to the browser. It is used for cross-browser testing and you can write the code in any language.
Selenium Web Driver is a better version of IDE and RC. It directly sends commands to the browser without the need of a server to be up and running.

Different languages can be used for coding the scripts like Java, C#, PHP, Python, Perl, and Ruby. Selenium Grid is used for parallel testing in multiple browsers and environments. It used the hub and node concept where hub acts as a source of Selenium commands and each node is connected to it.
Now, here we will discuss Selenium WebDriver. How a beginner can start learning Selenium WebDriver and how he can excel in it.
Now, first, we will look at the steps we need to follow to download Selenium Web Driver in your machine.

Ways to download and install Selenium WebDriver

  • You should have Java installed in your machine. This is the pre-requisite for Selenium Web Driver to work.
  • You can visit the page: http://seleniumhq.org/download/ and download the client drivers and language bindings. You have the select binding for Java.
  • This download will be named – selenium-2.25.0.zip.
  • Now, you can import all the Jars in Eclipse. You have to right click on the project and import jar files by selecting all the downloaded jar files. For this, you can click on the Libraries tab and then click on “Add External JARs”.

Now Let’s look the First Selenium WebDriver Script

Let’s take an example of the first Selenium Script which we would create using Selenium basic methods.
Let’s first look at the script in detail. In this script, we will do the following test steps.

  • Go to the home page of the test application
  • Verify the title of the page
  • Do a comparison of the result.
  • Close the browser after the script is done.

package projectSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class seleniumTest {
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”,”C:\\chromeDriver.exe”);
WebDriver driver = new ChromeDriver();
String baseUrl = “https://google.com”;
String expectedTitle = “Google”;
String actualTitle = “”;
        // launch Fire fox and direct it to the Base URL
driver.get(baseUrl);
        // get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page with the expected one and print
* the result as “Passed” or “Failed”
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println(“Test Passed!”);
} else {
System.out.println(“Test Failed”);
}
driver.close();
}
}

Things to look at the above code:

  • In the first two lines, we have imported two packages. You have to import – org.openqa.selenium and org.openqa.selenium.firefox.FirefoxDriver.
  • The most important step is to instantiate the browser. This is done by line

WebDriver driver = new ChromeDriver();
//This is done to invoke a chrome browser.
You can invoke a FireFox browser by following line of code
WebDriver driver = new FirefoxDriver();
You can invoke an IE browser by following line of code:
WebDriver driver = new InternetExplorerDriver ();
Also, while invoking a browser you have to pass the path of the executable file. You can do it by following line of code:
System.setProperty(“webdriver.chrome.driver”,”Path of chrome driver”);
System.setproperty(“webdriver.ie.driver”,”Path of ie driver”);

  • Get() method is used to enter a url in a browser.
  • getTitle() method of selenium webdriver is used to fetch the title of a web page.
  • Now, we have to compare the expected title with the actual title.

If(expectedTitle.equals(actualTitle))
{
System.out.println(“TEST PASSED”):
}

  • For terminating the browser, close() method is used. Driver.close() closes the active browser window. If you want to close all the opened browser windows by selenium web driver then you can use driver.quit().
  • You can run this test by right clicking on the program and then select as “Run As” as “Java Application”.
  • Next thing which is of utmost important while writing a test script is to identify web Elements which will be explained in detail in the below section.

Locating Web Elements

Locating web elements is very easy. Various selectors are available for that process. find Elements is one such 2 in which selenium webdriver is used for locating a web element and then, you can perform an action on that.

Know More: Selenium Automation Testing With Cucumber Integration

Let’s see some of the methods by which you can identify web element on a web page.

  • className – It will locate web element based on the class attribute. Eg: By.className(“abc”);
  • cssSelector – used to locate web element based on css selector engine. Eg:- By.cssSelector(“#abc”);
  • id – If some web element has id attribute, then you can directly identify the web element using id tag. Eg:- By.id(“abc”);
  • linkText – It will find a link element by text mentioned by you in the test script. By.linkText(“Login”);
  • name – If any web element has name attached to it then you can identify it using name attribute. Eg: By.name(“name”);
  • partialText – It will find a link element by text containing the text mentioned by you in the test script. By.partialText(“abc”);
  • tagName – It will locate all elements which will have this tag.
  • xpath – It is the most used locator in a selenium test script. It will identify the element using html path. It can be relative or absolute. Absolute xpath traverses the path of the web element by root and relative takes the reference of any web element and then traverse to that specified web element. It is better to refer an element by relative xpath rather than absolute xpath.

Basic Actions on a web element

You can click on a web element by using click() method of selenium web driver. You can locate a web element and then perform an action on it.
Eg: driver.findElement(By.xpath(“”)).click();
Also, you can send keys to a particular web element by using send Keys() method of selenium web driver. You can locate a web element and then you can enter some text in it using sendKeys() method.
Eg: driver.findElement(By.xpath(“”)).sendKeys(“name”);
Also, there are other actions which you can perform on a web element by using action class.
WebElement wb = driver.findElement(By.xpath(“”));
Actions actions = new Actions(Driver);
Actions.moveToElement(wb).build(). Perform ();
You can even switch to alert boxes which come when you click on some webelement. You can do it by switchTo().alert() method.
Eg code:
WebElement wb = driver.findElement(By.xpath(“”));
Wb.click();
Driver.switchTo().alert();
Now, you will be able to access the alert box. You can retrieve the message displayed in the text box by getting the text from it.
String alertMessage = driver.switchTo().alert().getText();
Also, you can accept the alert box by function accept(). You can see the sample code as below:
Driver.switchTo().alert().accept();
You can even check conditional operations on a web element.
Also, check whether a web element is enabled or not. If it will be enabled then you can do some operation on it.
Apart from all these, you can check if some web element is displayed or not. In the case of radio buttons, you can check if the radio button is selected or not. You can do these checks by – isEnabled(), isSelected() and isDisplayed() option.

Waits in Selenium Web Driver

Selenium Web Driver
If you want some step to get completed before any other step then you have to wait for the prior step to get completed. In manual testing, it is very easy to achieve but in automation testing, it is bit tedious and you have to wait for the previous step to get completed or a condition to be fulfilled before moving on wards to the next step.
This can be achieved by adding waits in between. There are two types of wait- explicit and implicit wait. If you are expecting a particular condition to be fulfilled before moving to the next step,
Another feature is that you can use explicit wait while if you just want a universal wait, then you can go ahead to use implicit wait. The implicit wait is used to set the default time out for the whole script.
A perfect automation script is made by adding both type of waits – Explicit and Implicit. You have to judiciously use both types of waits to make an efficient test case.

Know More : Top 50 Selenium Interview Questions and Answers

Explicit Wait

Syntax of Explicit Wait:
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“”));
Expected Condition can be used with so many conditions. Some conditions which can be used with it are:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Implicit Wait

Syntax of Implicit Wait:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
For this, you have to import a package into your code. The package name is java.util.concurrent.TimeUnit;

Selenium Intermediate Level Tutorial

Through the section Selenium Tutorial for Beginners, We gave you the basic info that you need to know about the tool. Now let’s go further and learn much more about this impeccable web app testing tool.
How to upload a file in Selenium test cases?
To upload a file, first, you have to identify the element on which you have to upload your file. There you can directly use sendKeys() function of selenium web driver. You can pass the path of the location in sendKeys. In this way, you will be able to upload a file using selenium web driver.

public static void main(String[] args) {
System.setProperty(“webdriver.gecko.driver”,”path of gecko driver”);
String baseUrl = “http://www.google.com /upload/”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement element = driver.findElement(By.id(“id of element”));
uploadElement.sendKeys(“C:\\newhtml.html”);
//Here,  above you have to pass the path of the file where your file is located.
// Then you can click the upload file link
driver.findElement(By.xpath(“”)).click();
}
How to use a web table in selenium script
You have to access a web table and the elements present in the table. You can get it by making an xpath. Suppose you have had1 0a table with four blocks.
selenium intermediate tutorial
The first thing which you have to do is to find the XPath of the web element in this web table. Let’s say you want to get to the third element in the above web element.
The coding of the above web table is as below:

Selenium Intermediate Level TutorialSelenium Intermediate Level Tutorial
Now, you can analyze that first there is a table and then there is a tbody. In that tbody there are two rows. One row is having two tables. The first row is having two cells – First and Second. The second row is having two cells – Third and Fourth.
Our goal is to reach to the third cell. Let’s try to make the XPath of it.
The XPath of it will be //table/tbody/tr[2]/td[1]
So, the table is the parent node from which we will iterate to go the third element. From there, we will go to the tbody section and then the second row. From there we will get the first column.
Let’s write a script to get the text out of it.
public static void main(String[] args) {
String url = “http://testsite.com/test/write-xpath-table.html”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
String txtWebelement = driver.findElement( By.xpath(“//table/tbody/tr[2]/td[1]”).getText();
System.out.println(txtWebelement);
driver.close();
}
}
Let’s take an example of a nested web table. You have to then analyze it carefully and get the XPath of it. Let’s look at the example below to get more information on it.
Selenium Intermediate Level Tutorial:
So, if you want to access the web element which is having text 10-11-12 then you can do it by traversing from the table and then iterating through the rows and columns to reach there.
Xpath would be: //table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]
public static void main(String[] args) {
String url = “http://testsite.com/test/write-xpath-table.html”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
String txtWebelement = driver.findElement( By.xpath(“//table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]
”)getText();
System.out.println(txtWebelement);
driver.close();
}
}
This way, you can iterate through the rows and columns to reach to a specific cell from a web table.
Now, one of the most important concepts in selenium which will help you in many cases when you won’t be retrieving any text from a web element or to enable a web element to get the text or to perform any action on it.
Let’s talk about JavaScript Executor in detail. It is an interface which helps to execute javascript.
JavaScript Executor
Sometimes you are not able to click on a web element using click() function. You can then use javascript executor to execute click function on a web element. Let’s have a look at the code.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
You can now click on a webelement using below command.
WebElement button = driver.findElement(By.xpath(“”));
Js.executeScript(“arguments[0].click();”,button);
Also, if send keys isn’t working. You can make use of java script executor to send keys. Let’s look at the example below.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“document.getElementById(‘id’).value=”value;”);
You can even make use of java script executor to refresh a web page. You can do it by following command:
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
Sometimes, getText() doesn’t work and then you have to make use of java script executor to get text of a web element. You can do it by following line of code:
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
Sysout(js.executeScript(“return document.documentElement.innerText;”).toString());
You can even get the title and URL of a web page using java script executor. The procedure is very simple. Let’s have a look at the following lines of code.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
System.out.println(js.executeScript(“return document.title;”).toString());
System.out.println(js.executeScript(“return document.URL;”).toString());
Desired Capabilities Concept in selenium web driver
You can make the set of configurations on which you want a particular test script to run. You can pass browser name, version to specify the type of environment on which you want a test case to run.
Let’s see some of the capabilities which you can set in a test case for IE browser.
//it is used to define IE capability
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, “IE”);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
In the above capability, we have passed the capability browser name and we have ignored the security domain.
After setting the capabilities you can pass the capabilities to the web driver instance so that it executes the test on a particular configuration.
Let’s have a look at the complete set of code.
public static void main(String[] args) {
//it is used to define IE capability
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, “IE”);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
System.setProperty(“webdriver.ie.driver”, “path of executable”);
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get(“http://gmail.com”);
driver.quit();
}
Handling a drop down in selenium web driver
You have to first import following packages: org.openqa.selenium.support.ui.Select.
First, you have to identify from DOM whether the dropdown is of select type or not. If it is of select type then you have to go for the below steps.
Then, you have to uniquely identify the select tag. You have to first make the object of Select class and pass the element for which you have to choose the options from the drop-down.
Select dropdown = new Select(driver.findElement(By.xpath(“”)));
Now, there are three main methods which you have to use to select any element from this select object.

  1. selectByVisibleText
  2. selectByIndex
  3. selectByValue

You can either select any element from this drop-down by matching the visible text with that of the text passed by you. You can also select any web element from the drop-down using an index. Last option is to select by value tag.
Also, there are some more functions which are available. Some of them are selectAll() and deselectAll() too select and deselect all the elements when more than one element can be selected.
But, if the dropdown is not of select type then you can’t go for the conventional method. You have to follow another method. You have to uniquely identify the web element on which you have to select a dropdown option. You can identify it and the sendKeys() function of selenium web driver to send keys to the uniquely identified dropdown.
WebElement dropdown = driver.findElement(By.xpath(“”));
Dropdown.sendKeys(“value to be selected”);
How to select the checkbox and radio button is selenium
Sometimes, you come across situations where you have to select checkboxes and radio buttons. You can do it easily with selenium web driver. You just have to use click() function of web driver to click on checkbox and radio button. You can even check of the web element is selected or not.
.isSelected() checks if any web element is selected or not.
It gives false if the web element is not selected and it gives true if the web element is selected.
This way, you can handle radio buttons and checkboxes in a selenium script.

Selenium Advanced level Tutorial

Now, you know almost the stuff which is required for selenium intermediate and beginner level. Now, you are proficient enough to deal with all the advanced level of selenium web driver. You can then practice those and while you are done with those, you can move forward to the advanced level of course.
Let’s see what lies ahead and what can give you an edge in your interviews. You can look at this advanced course so that you can be ahead of all the candidates who just know the basic and intermediate selenium course. Let’s have a look at Selenium Advanced level Tutorial

Selenium Grid


Selenium Grid is issued for running various tests on different browsers, operating systems, and machines in parallel. It used a hub and node concept. You don’t want test cases to run on a single machine. You have your machine as a hub and various systems on which test cases will be distributed. You call those machines as nodes.
The hub is the central point and there should be only one hub in a system. This hub is your machine from which you want to distribute the test cases among all the clients.
This is the machine on which test cases will run and those will be executed on the nodes. There can be more than one node. Nodes can have different configurations with different platforms and browsers.
Let’s see how you can establish a selenium grid in your machine.
You can download the selenium grid server from the official site. You can place Selenium server.jar in a hard drive. You have to place it in all nodes and hub c drive.
Open the command prompt in your hub and then, go to C directory. There you have to fire the below command java -jar selenium-server-standalone-2.30.0.jar -role hub
Now, if you want to check if the selenium grid server is running on localhost that is 4040 port or not. You can visit the local host on your browser.
You have to then go to C directory of the node and open command prompt in it. Also, when you have made the selenium grid server up in the hub, you have to note down the IP address and port.
java -Dwebdriver.gecko.driver=”C:\geckodriver.exe” -jar selenium-server-standalone-3.4.0.jar -role webdriver -hub ip address of hub -port port number of hub
When you fire the above command, again go to hub browser and the port number 4040. Refresh the page and you will see IP address which will be linked to the hub.
Now, you have set up machines with different configurations. But how would the hub know which test case would be run on which node.
This will be done by desired capabilities which will tell that this test script would run on a particular set of configuration.
One can do it using below source code:
This way, you will be able to distribute the test cases across different machines and browsers. You will be able to do parallel testing using Selenium Grid.

Maven and Jenkins Integration with Selenium


Maven is a build management tool which is used to make the build process easy. Maven avoids hard coding of jars and you can easily share the project structure across the team using artifact and version id.
Every team member would be at the same page. You can make a maven project by going to File – New – Other – Maven project. You have to then specify the artifact id and then version id. You will be prompted to select a template. For starting, select a quik start template.
You will get a folder structure where you will be having two folders – src/main/java and src/main/test. In java folder, you will maintain all other stuff except tests while in test folder you will maintain all the test cases.
You will be having pom.xml file where you have to define all the dependencies so that it can download from the maven repository and place them in ./m2 repository in your local project structure.
You can get the dependency from the maven official site and then place in pom.xml. It will download all the required jars.
Also, Jenkins issued for continuous integration of the latest build with the production environment. Whenever a developer will fire the latest build then the smoke test will start running on that build.
If the build gets passed then it can be deployed to the production else the developer and tester would get a notification about the failed build. It makes the delivery cycle very fast.
Also, you can do it by downloading Jenkins war file and then running it so that Jenkins server will be up and running on port number 4040.

After doing that you can install all the necessary plug-ins. You can then create a new item and does the post-build actions.
Also, you can pass the path of git repository from which it will fetch the latest build. If you are using a local server then you pass the path of pom.xml from the system.
You can even set nightly runs with Jenkins, You have to specify the time when you want your test to run. They will run and you will get the reports on the Jenkins server the next morning. Isn’t it time-saving?

Database Testing using Selenium WebDriver

Integrating Selenium tests to the database is so easy in the latest version of the tool. You have to make use of JDBC library for database connections. It allows connection of Java and databases. First, make a connection to the database with the following command:

DriverManager.getConnection(URL, “userid”, “password” )
After doing that you can load the JDBC driver. You can do it by following lines of code:
Class.forName(“com.mysql.jdbc.Driver”);
Now, you have to send the query to the database. How will you do it? You can create an object of a statement class and then execute the query using the statement object.
Statement stmt = con.createStatement();
stmt.executeQuery(select *  from employee;);
Now, you can get the result in the result set. You can do it by following command:
ResultSet rs= stmt.executeQuery(query);
After doing all the operations, you can close the connection.
Con.close();
In this way, you can get the result set and then do all the validations on the result set.

How to take screenshots in selenium web driver

You should get the screenshot of the failed test cases so that you can get to know where exactly is the problem. This will help in better-debugging skills.

Let’s look at the steps involved in taking a screenshot:
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
This step caste a driver instances to Takes Screenshot interface. Now, you have one method which is getting screenshots which will get the image file.
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Now, you have taken the screenshot but you have to place it somewhere. You can create some folder which will be used for storing all the screenshots captured during the execution.
You can do it by following the line of code:
FileUtils.copyFile(SrcFile, DestFile);
This is the way to capture screenshots. But if you want that only the screenshot is taken when a test case fails. You can use ITestListener.
It has various methods and one of the methods is onFailure() which will do the specified task when every there is any failure in a test case.
So you can put this code in that method so that whenever any test fails it will take the screenshot and place it in the folder specified by you.

How to drag and drop in a web page using Selenium Web driver

Now if you want o drag and drop something o a web page, you would be confused. It is very simple. You have to make use of Actions class which gives you a method dragAndDrop() which will drag and drop a web element from a source destination to the desired destination.
Actions actions = new Actions(driver);
Actions. dragAndDrop(Sourcelocator, Destinationlocator).build().perform();
Make sure that the source locator and destination locator have correct xpaths. In this way, you will be able to drag and drop any element on a web page.

How to do right click and double click on a web page

You can do a right-click on a web page using Actions class. Actions class provides a doubleClick method which allows to double click on a web element. You can do it by following lines of code:

Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id(“ID”));
actions.doubleClick(elementLocator).perform();
You have to do right-click in selenium using action class only. It is very easy. It provides a method – contextClick() and then right click on a web element.
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id(“ID”));
actions.contextClick(elementLocator).perform();
This way, you will be able to right click and double click on a web element.
How to switch to an iFrame

iFrame is a web page which is embedded into another web page. Whenever you want to click on a web element, which is in another iframe. First, you have to switch to that iframe and then perform an action on it.
You can do switching by
Driver.switchTo().frame(index or name or id of iframe);
Conclusion
Before learning Selenium it’s better to have a thorough understanding of any object-oriented language. languages that Selenium support includes, Java, Perl, C#,  PHP, Ruby, and Python Currently.
We genuinely hope this tutorial has helped in understanding selenium better.

Get a eBook : Download PDF

Test Case Management in jira: How to do it?

Are you still slogging on to excel sheets to manage test cases?  Gone are the days when excel sheets were the only tool available to manage test cases. With the outburst of JIRA software, 66% of testers today leverage it to their benefit. So, why should you lag behind?

Going forward in this article we will discuss, everything that you should know to leverage JIRA Software for Test Case Management.

A quick overview of JIRA software

JIRA software is a product of Atlassian Corporation, an Australian enterprise software company. It is largely used for issue tracking, bug tracking, and project management. But many teams are now using it as a Test case manager as it allows testers and developers to remain at one platform. But, how can you use it for Test case management? Let’s check it out.

There are two ways that can help you to use JIRA for Test case management by:

1.    Configuring JIRA for Test case management

2.    Incorporating testing tools with JIRA

But before moving forward let’s have a look at various features of JIRA that assist test case management.

  • JIRA can help in manual testing and is a great tool for it.
  • Associated with defects and requirements.
  • Supports issue types such as user story and test case.
  • Offers multiple fixes for different versions.
  • Supports both manual and automatic issue assignment.
  • JIRA Workflow has the power to control developers, QA and tester actions.
  • Can incorporate source code.
  • Offers reporting facility.
  • Easy to customize.
https://www.youtube.com/watch?v=sGdVEbHTI1A

1.    How to Customize JIRA for TCM?

You can customize JIRA software for test management in either of the ways:

  1. Using the “User story”
  2. Adding a “Test Case” issue

You can configure your JIRA software for test case management by using the User Story. Here’s how to proceed with it:

  • Generate a user story to act as a test case.
  • Further, add subtasks referring back to the user story (your subtasks here act as test cases or test runs)
  • If all the subtasks pass, then your user story is good to go for production. 

This approach raises a few challenges. The main challenges that you can face are:

  •  When you have to reuse the test cases: In JIRA software if you finish working on any issue, it is marked done and is closed. To reopen it and to convert it into the test case format requires a lot of efforts and maintenance overhead. So if you want to use any test case again, it becomes very complex.
  • When you have to align test cases: If you have multiple test cases that link to several user stories, it gets very difficult to align them.

Creating a Test Case Issue Type

You can configure your JIRA software for test case management by creating a Test Case issue type. Here’s how to proceed with it:

  • Add a test case issue type.
  • Add the required steps for testing.
  • Assign your test case as parent issue.
  • Create and label subtasks as “Test Run”.
  • Add outcomes, the assignee to run the test cases, the affected version under the “Test Run” subtask.

But creating a test case issue type possesses few challenges for the user. Here are the few challenges that can be faced by you:

  • When you have to reuse the test cases: As discussed above reusing test cases is a very complex process. 
  • When you have to rerun test cases: JIRA software requires you to add subtasks every time you have to run a test case.
  • When you have to create coverage reports: In JIRA software all the subtasks are mostly assigned under one issue. It is not possible to group various test runs to different configurations and to create a coverage report. 

2.    Incorporating testing tools with JIRA

Since JIRA is not custom made for test case management it possesses many limitations. To devoid it of its limitations, you can incorporate various testing tools with JIRA.

You can add testing functionalities to JIRA by the following two ways:

1.    Using Ad-ons

2.    By external integration of testing tools

  1. Using Ad-ons

Various Ad-ons are available on Atlassian Marketplace that helps enhance the functionalities of JIRA as a test case manager.

Eg: Zephyr for JIRA and Xray for JIRA promotes manual test execution.

qTest Scenario and Behave Pro assist TDD, BDD, and ATDD testing

  • Integrating test case management tools to JIRA

Test case management is one of the major tasks of STLC. Using an apt test case management tool can save you both on time and efforts. A number of test case management tools are available in the markets that can be externally integrated with JIRA, resulting in better test case management.

How can test case management tools help you?

  • They can help you to consolidate all your executions while you can also use JIRA.
  •  They can help you eliminate one of the biggest drawbacks of JIRA – reusing test cases. With test management tools you can reuse executions and help in better execution setup.
  •  They enhance the capabilities of JIRA by keeping the complete execution history inside JIRA.
  • They permit numerous test runs of the test cases with different configurations, assignees, results, etc.

Though deploying dedicated test case management system with JIRA offers the best experience. It also possesses some drawbacks. You can eliminate it by using the solution that offers the most optimal integration experience based on your requirements. 

Conclusion

The choice to pick one of the above-mentioned methods depends entirely on your requirements. We have curated a chart to help you judge your preference.

alt

Selenium Automation Testing With Cucumber Integration

Selenium is a Web Automation Tool and can be used to do regressive automated testing to test any web application.
app testing
Selenium is a power tool though it lacks an ability to bridge the gap between business analyst and technical personnel.
If we follow the old requirement gathering process and obsolete software life cycle then there are maximum chances of building a completely different product as to what client expected.
This happens because of mis-interpretations and Cucumber solves them all. Cucumber is BDD driven framework which test any application on the basis of its behaviour.
It uses Simple Gherkin language which is easy to understand and communication gap would be eliminated.

Video Courtesy : Execute Automation
In this video we will be talking about an introduction to Cucumber and also an high level introduction on BDD and Gherkin.
Prerequisites for using Cucumber
 Before using Cucumber you should have some prerequisites in your system else Cucumber won’t run. Let’s see what those prerequisites are.
1. Selenium Jars.
2. Cucumber Jars : You can download from here. For other jars, just search in Maven repository and either you can download them or add their dependencies in your pom.xml. Following Jars are required:

  • cucumber-core
  • cucumber-java
  • cucumber-junit
  • cucumber-jvm-deps
  • cucumber-reporting
  • gherkin
  • junit
  • mockito-all
  • cobertura

3. Download Cucumber Eclipse plugin in Eclipse from Eclipse Marketplace.
First Project with Cucumber and Selenium
 Now let’s start with Cucumber and Selenium.

  • Create a Java Project with name “CucumberProject” in Eclipse.
  • Add all jars what you have downloaded in earlier section.
  • You can add Jars by clicking on Project -> Properties -> Java Build Path.
  • Now, you are all set to start with Cucumber Feature File. One can make Feature file by first creating a features folder inside the Project. Now, you can create a file inside the folder “Features” with name as “FirstTest.feature”.
  • Your first file is created and now you can start writing scenarios in it to test your web application.

Feature: Reset functionality on login page of Application
Scenario: Verification of Reset button
Given Open Google Chrome and launch the site
When Enter Username and Password
Then Reset the credential
And Close the Browser
The above Scenario explains you about the reset functionality. Line 1 tells you to open a browser which is Google Chrome and launch a a particular application. Next line says to enter the credentials in application. 3rd line says to reset the credentials and then close the browser.

  • Now, you need a test runner to run the feature file because feature file can’t run by itself. First you have to make a RunnerTest Package and then create a testRunner.java class in it.

package RunnerTest ;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features=”Features”,glue={“StepDefinition”})
public class testRunner
{
}

Also Read : 15 Top Selenium WebDriver Commands For Test Automation

Annotations are used to start executing the test. @RunWith annotations helps in executing the test and @CucumberOptions  annotations is used to set properties of your cucumber tests.

  • Now your Feature file is ready and runner file as well. Now comes the test of actual implementation of the steps defined in the scenario. The file in which you will write the implementation of the steps of scenario is called Step Definition file.

Make a package named as StepDefinition in your Project Structure and add “TestSteps.java” file in it. Here, you will actually write your test script to test the application.
package StepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class TestSteps {
WebDriver driver;
@Given(“^Open Google Chrome and launch the site$”)
public void open_the_Firefox_and_launch_the_application() throws Throwable
{
System.setProperty(“webdriver.chrome.driver”,”Path of Chrome.exe file”);
driver = new ChromeDriver();
driver.manage().window().maximize();
Driver.get(“URL”);
System.out.println(“This Step open Chrome and launch the site.”);
}
@When(“^Enter Username and Password$”)
public void enter_the_Username_and_Password() throws Throwable
{
driver.findElement(By.name(“uid”)).sendKeys(“username”);
driver.findElement(By.name(“password”)).sendKeys(“password”);
System.out.println(“This step enter the credentials on the login page.”);
}
@Then(“^Reset the credential$”)
public void Reset_the_credential() throws Throwable
{
driver.findElement(By.name(“btnReset”)).click();
System.out.println(“This step click on the Reset button.”);
}
@Then(“^Close the Browser$”)
Public void Close_the_browser() throws Throwwable
{
driver.close();
System.out.println(“This step closes the browser”);
}
}
There are 5 main annotation tags which are uses in Cucumber:

  • Given : This is used for a pre condition.
  • When : This is used for an action which occurs after a pre condition.
  • Then : This occurs for a reaction for an event.
  • And: This adds a particular step in addition to the defined above.
  • But : This adds a negative step.

 
banner
Whatever tags you will be using in Feature file; you will have to use the same tags in the step definition file. In this way each scenario would be mapped with the test steps defined in the step definition file.

  • Now comes the main step, how to run these files. You can run the feature files by right clicking on Test Runner file and click on “Run with” JUnit Test. When you will execute your test feature file you will observe that the Selenium test scripts start running and System.out.println is printing on the console.

Thus, you ran your tests script for a set of data with Cucumber. But if there is a scenario where you want data driven testing or you want to run the same scenario for three times and then only you can pass the data from feature file itself.
Feature: Reset functionality on login page of Application with 2 sets of data
Scenario: Verification of Reset button
Given Open Google Chrome and launch the site
When Enter Username and Password
|username | password |
|user1    | pass1    |
|user2    | pass2    |
Then Reset the credential
And Close the Brows
@When(“^Enter the Username \”(.*)\” and Password \”(.*)\”$”)
public void enter_the_Username_and_Password(String username,String password) throws Throwable
{
driver.findElement(By.name(“uid”)).sendKeys(username);
driver.findElement(By.name(“password”)).sendKeys(password);
}
Only this step needs to be edited and the whole scenario would run for two number of times. This is called data driven testing with Cucumber.
Conclusion
Cucumber is a great tool used for BDD driven testing. This helps to make business analyst, client and technical people at a same level and thus bugs would decrease and the application will become more stable.
You just need to create simple Feature files which is written in English language ( Gherkin ) and thus your test scripts are ready.

Also Read10 Key Factors for Successful Test Automation

How to Integrate Selenium With Gecko Driver : Full Tutorial

Mozilla Firefox browser’s versions greater than 47.0 were not compatible with Selenium WebDriver 2.53.0 or 2.53.1 that means Firefox browsers version after 47.0 can’t be used in Selenium without any drivers. As of version 3.0, the Selenium uses a driver to form a link with Firefox browser. This driver is known as Gecko Driver.

Before starting with the GeckoDriver you need to understand what is GeckoDriver, why it is required in Selenium WebDriver? Or how can it be used in Selenium? Let us start with the very basics.
What is a Web Browser Engine and What is Gecko Driver?
Web browser engine is a software program that is used to control and enter the content such as HTML, CSS, XML, images etc.
On the browser and therefore it is also known as layout engine or rendering engine. It is a component of browsers and helps in displaying web-content.
Gecko is a web browser engine which is developed by Mozilla Foundation and is written in C++. It is an open source engine which can be easily available for the user.
GeckoDriver is a proxy which is used to interact with the browsers (such as Firefox) that run the Gecko browser engine. GeckoDriver provides an HTTP API to communicate with Gecko browsers (like Firefox version 47 onwards).
Why Selenium Needs Gecko Driver?
Until Selenium version 2, it had Firefox driver which were used to interact with the Firefox browser (version till 47).
Now, Firefox (with Firefox browser version 48 onwards) has done some changes and due to some security reasons, it does not allow any third party driver to directly interact with the browser.
Also Read : How to Integrate Maven and Jenkins with Selenium 
That means the user cannot use Firefox driver of selenium version 2 to interact with the browser version 48 onwards.
Thus, we need Selenium 3 which has marionette drivers and with this user can directly interact with the Firefox browsers using a proxy which is GeckoDriver. Marionette driver is an automation driver for Mozilla’s Gecko engine.
Getting Started with GeckoDriver
This section will help you to install Selenium 3 Jars and GeckoDriver for Firefox browser. Below are the steps which you need to follow:
Step 1: To Add Selenium 3 jars
If you are using Selenium 2 jars, you can easily upgrade it to Selenium 3 Jars by following this link.
www.seleniumhq.org
Click on download option and you will find “Version 3.0.1” to download. Click on the link to download Selenium 3 jar.
Now, copy this jar file by using ‘CTRL + C’ and go to your selenium tool. You will find ‘lib folder’ in test explorer.
Select ‘lib folder’ and right click to open options and select New > Folder and set folder name as ‘selenium3jars’ to make it easily accessible or whatever name you want to use.
You will see, the ‘selenium3jars’ folder is created as a children folder under ‘lib folder’. Use ‘CTRL + V’ to paste selenium 3 jar file that you copied earlier and paste inside ‘selenium3jars folder’.
You’ll see the jar file has been successfully copied to the folder. Next thing you need to do is to add this jar file into your project. You need to select Selenium 3 jar file and right click to open the options palette. Then left click on Build Path > Add to Build Path to add jar file into your project easily.
You’ll see that Selenium 3 jar has been added to Referenced libraries that mean your selenium is ready to execute the tests via the driver.
Step 2: Installing Gecko Driver
To download GeckoDriver for your WebDriver you need to follow this link.
https://github.com/mozilla/geckodriver/releases
If you are running 32bit or 64bit Windows, MACOS, or Linux you can easily download the file which is compatible with your operating system.
You’ll see many versions to download, but you can choose the latest version from the options. You can easily download this zip file to your computer by clicking on the appropriate link.
If you are using windows operating system, you can download either win32.zip or win64.zip and if you are using MAC operating system then you can choose macos.tar.zip.
After downloading the zip file you can simply extract it in your preferred location and then copy the GeckoDriver.exe file using ‘CTRL + C’.
Again, you have to follow the same procedure to copy this file in the ‘lib folder’.
Go to Selenium and select the lib directory from the test explorer. Again, right-click to open option palette then left click on New > Folder to create a new folder.
automation testing
Then set the name as ‘geckodriver’ or any other name which is easier for you to recognize and click ‘Finish’. Then you have to add a GeckoDriver.exe file into the folder you have just created.
After adding a geckodriver.exe file to a folder, the next step is to use the following syntax to show the exact location of the executable file.
Syntax

System.setProperty(webdriver.gecko.driver”, ”location of gecko driver executable”);

You need to enter the exact location of the executable file in the above syntax. To see the location of your file, you can select a geckodriver.exe file from the folder and right click to open the options palette. Then left click on the properties to open details.
Select the location and copy all. Use this location address to enter this address in the syntax. For instance:

System.setProperty(“webdriver gecko driver”, “C:/Users/raghav/Desktop/Tools/Eclipse/Selenium/SeleniumTest/lib/geckodriver/geckodriver.exe”);

If you find it difficult to add the location manually or showing any unwanted errors, you can also use an alternative method to add an executable file to your project.
Go to your computer and search the above location in the file explorer. Then copy the executable file from the downloaded folder to the current address location.
Left click and drag the executable file from the download folder to the location of the searched folder. The dialogue box will appear saying to replace it or not. Click on replace button and copy the .exe file to the folder.
Step 3: Adding Latest Version of Firefox Browser
Download the latest version of Firefox by following this link
https://filehippo.com/download_firefox/
In the next step, you need to add the syntax and also the location of this browser.
Syntax

System.setProperty(webdriver.Firefox.bin”, “Location of Firefox exe”);

Again, you need to enter this syntax in your selenium tool and also the exact location of the Firefox.exe file.
To know the exact address of the .exe file you can select firefox.exe and right click to open option palette. Then left click on properties to know the location.
Copy the location and enter this address in the syntax. For instance:

System.setProperty(webdriver.Firefox.bin”, “C:\Program Files\Mozilla Firefox\firefox.exe”);

Use of Gecko Driver to Launch Firefox Browser

import org.openqa.selenium.WebDriver;[]
public class FirstSeleniumTest {
public static void main(String[] args) {
System.setProperty(“webdriver gecko driver”,      “C:/Users/raghav/Desktop/Tools/Eclipse/Selenium/SeleniumTest/lib/geckodriver/geckodriver.exe”);
System.setProperty(webdriver.Firefox.bin”, “C:\Program Files\Mozilla Firefox\firefox.exe”);
 WebDriver driver = new FirefoxDriver();
driver.get(Http://www.google.com/);

This code is used to generate a test for Firefox browser when executed. It will open the Firefox browser and go to the link which is specified in the code.
In this test, the Firefox will open selenium.org website and after successful loading of the file, the test will close the Firefox browser and execution will be completed.
You need to remember, if you want to move your project to a new location, the current address which you have specified in order to add Firefox.exe and geckodriver.exe will not run.
You need to specify their location again if you wish to move your project location.
Understanding the Code
1. Import org.openqa.selenium.WebDriver: This syntax is used to import every reference which is needed for the WebDriver This WebDriver is later needed to represent the new browser.
2. setProperty: This syntax is used to set the system property to have some value. The browser does not have its own inbuilt server which can run the automation code. Therefore, System.setProperty is needed for the browser to set a respective path.
3. WebDriver driver = new FirefoxDriver(): This syntax is generally an interface which contains methods defined by the user to perform on the Firefox browser.
4. get(http://www.google.com): This syntax will lead the browser to go to the specified link and open it.
Additional Tips:

  • Always run automation on a separate browser version
  • Use selenium 3 with latest (stable) version of Firefox
  • Have Java 8 or higher for Selenium 3

Why is TestNG Awesome? Advantages of Integrating it with Selenium

Basically, TestNG is a user – friendly automation framework that overcomes the drawbacks and limitations of Java Unit, thus introducing the entire new set of features which makes it more powerful and useful.

This automated testing framework helps in elimination of numerous limitation of the older framework. It facilitates the developer the ability to write more flexible and powerful tests.
TestNG Framework

  • TestNG is a testing framework designed for unit testing. Today it is used for every kind of testing.
  • Initially, it is developed to simplify a broad range of testing, no matter from system testing or Unit testing.
  • It is an open source framework which is inspired from the Java platform (JUnit) and NET platform (NUnit).
  • It can be used for any testing, be it API testing or UI testing.
  • It is introduced as a brand new automated framework whose functionalities make it more powerful and easier to use.

Features of TestNG

  • Maintains flexible runtime configuration.
  • Guards easy going plug-in API.
  • Supports Multi threaded testing.
  • Upholds parallel testing, group testing, partial testing and load testing.
  • Supports annotations of JUnit and have some more annotations to make testing easier.
  • Separates compile-time test code from run-time configuration/data info.
  • Supports testing integrated classes.
  • TestNG supports the ‘dependence’ method which is not available in JUnit.

How to Download or Install TestNG for a project
Before performing this step by step process, do not forget to visit these prerequisites to install selenium IDE.
In order to download TestNG plug-in, all you need to have is a selenium IDE and Active internet connection. But, if selenium IDE is already installed in your system, then follow these simple steps:
Step 1: Download and install the Java Software Development Kit (JDK)
Step 2: Download “Eclipse IDE for Java Developers”. You choose 32 bit or 64 bit as per your requirement.
Step 3: You can download the Selenium Java Client Driver. There would be different languages, choose only the Java from the options.
Step 4: Configure Eclipse IDE with Web Driver.
TestNG Basic Annotations
Annotations are a new feature in Java provided by JDK 5.0 version. Annotations can be used to describe metadata in java programs. To describe any information about the coding part, annotations are used. Following is the list of annotations usually used in TestNG:

Sr. No. Annotation Description
1. @BeforeSuite This annotation will always be executed before all tests are run inside a TestNG.
2. @AfterSuite This annotation will always be executed after all tests are run inside a TestNG.
3. @BeforeClass This annotation will always be executed before the first test method in a class is called on.
4. @AfterClass This annotation will always be executed after the first test method in a class is called on.
5. @BeforeTest Executed before any test method associated with the class inside <test> tag is run.
6. @AfterTest This annotation will always be executed before any test method associated with the class inside <test> tag is run.
7. @BeforeGroups This annotation will always be executed before the first test method associated with these groups is called on.
8. @Aftergroups This annotation will always be executed shortly after the first test method associated with these groups is called on.
9. @BeforeMethod This annotation will always be executed before each test method.
10. @AfterMethod This annotation will always be executed after each test method.
11. @DataProvider This annotation must return object [ ], it marks a method as supplying data for a test method.
12. @Factory This annotation will return the object and marks a method as a factory that will be used by TestNG as test classes.
13. @Listeners This annotation defines the listeners on a test class.
14. @parameters This annotation describes how parameters can be passed to a test method.
15. @Test This annotation marks a class as a part of the test.

Execution Procedure of Methods in TestNG with Annotations

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;
 
public class TestngAnnotation {
// Case 1
@Test
public void testCase1() {
System.out.println(“Case I”);
}
// Case 2
@Test
public void testCase1() {
System.out.println(“Case II”);
}
@BeforeMethod
public void beforeMethod() {
System.out.println(“Before Method Annotation”);
}
@AfterMethod
public void afterMethod() {
System.out.println(“After Method Annotation”);
}
@BeforeClass
public void beforeClass() {
System.out.println(“Before Class Annotation”);
}
@AfterClass
public void afterClass() {
System.out.println(“After Class Annotation”);
}
@BeforeTest
public void beforeTest() {
System.out.println(“Before Test Annotation”);
}
@AfterTest
public void afterTest() {
System.out.println(“After Test Annotation”);
}
@BeforeSuite
public void beforeSuite() {
System.out.println(“Before Suite Annotation”);
}
@AfterSuite
public void afterSuite() {
System.out.println(“After Suite Annotation”);
}
}
Creating XML file in C:\>TestNG for executing annotations
<?xml version = “1.0” encoding = “UTF-8”?>
<!DOCTYPE suite SYSTEM “http://demo” >
<suite name = “Suite1”>
<test name = “test1”>
<classes>
<class name = “Annotation”/>
</classes>
</test>
</suite>
Test case compilation using javac
C:\TestNG>javac Annotation.java
Output:
Before Suite Annotation
Before Test Annotation
Before Class Annotation
Before Method Annotation
Case I
After Method Annotation
Before Method Annotation
Case II
After Method Annotation
After Class Annotation
After Test Annotation
After Suite Annotation
===============================================
Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Why use TestNG with Selenium?
Selenium tests alone cannot generate a proper format for the test results. However, with the help of TestNG, you can generate the proper format for the test results.

Read also :  10 Best Automation Testing Tools of 2018

TestNG is widely used by other selenium users because of its features and feasibility. Moreover, it is associated with several advantages through which a user can be very comfortable to leverage TestNG.
Following are the points why you need to use TestNG with selenium:

  • You don’t have to write a single line of code to generate a proper format for the test results as they are generated by default. The report usually includes a number of test cases runs or a number of test cases that failed or passed.
  • If you want to control the test executions, then you have access to multiple annotations which can control how the test can be run.
  • You can run your tests in arbitrarily big threads pools. You can simply group multiple test cases and convert them into an XML file and then set the priority of test case in a specific order.
  • It provides easy and flexible test configuration in which you don’t have to write a code to modify any test methods.
  • Using it you can create data-driven frameworks. You can use the @DataProvider annotation to support data-driven testing.
  • If you want to run your tests based on the parameters, TestNG supports parameter feature which will make your test cases or test suite very flexible. You can easily pass the parameter at runtime so that based on the requirement you can pass the parameter and you don’t have to modify your existing test.
  • If you have multiple classes to execute in the test suite, you can directly right click and run the complete test suite.
  • It is supported by a variety of tools and plugins. Also, it supports multiple IDE such as Webstorm, IntelliJ or NetBeans.
  • You can simply group the test cases with the use of TestNG. Suppose you have four categories of smoke, recreation, functional and non-functional. You can group all of these test cases and can run them individually.

Advantages of TestNG over JUnit                     
app testing

  • It gives an option to run out same test case with multiple sets of test data.
  • It provides default reports which are not provided if you are using JUnit.
  • It has a higher level of customization which enables the user to customize test case execution so that the user can run his script when something happens.
  • Test cases can also be grouped easily as compared to JUnit.
  • The annotations used in TestNG are very simple and easy to understand.

 

How to Integrate Maven and Jenkins with Selenium 

Using Selenium test scripts is easy but when it comes to build management and Continuous integration, Selenium alone is not that powerful.That’s why we integrate Maven and Jenkins with Selenium

You need to take help of other tools to integrate Continuous integration and deployment. This is exactly why Maven and Jenkins are needed.
What are Maven and Jenkins?
Jenkins is an open source continuous integration tool and it is cross platform which can be used on Windows, Linux, MAC and Solaris environment.
Jenkin will monitor a job which can be SVN checkout, cron or any application state.
It then fires an action when a particular step occurs in a job. Maven is a build management tool which makes the build process very easy.
With the help of maven you can define your project structure, dependencies and builds.
With the help of pom.xml you can define all the dependencies which would ease the process of build.
Maven automatically download the necessary files from maven repository and place them in. /m2 repository. Hence, we require Maven and Jenkins with Selenium.
Advantages of Using Maven and Jenkins

  • Jenkins provides a way to do smoke testing for every time the code changes and deployed to a new environment. It will make sure that the code is running properly.
  • You cans schedule your test cases with Jenkins so that if regression suite takes almost 6-7 hours to run then you can have nightly build run so that by the time you reach office it will be done.
  • Jenkins server will act as a common server for client as well as technical people to logon to it and see all test reports and test execution history.
  • Maven in turn reduces dependency on hard coding of jars.
  • Maven can make the build process very easy.
  • Also, at some time if you need to update the jars with a specific number, you don’t need to go to Build path and add that particular jar. You can just change the number of version in pom.xml and it will be done.
  • In a team where people are distributed across geographical locations it is easy to share artefact id and version id to clone the project rather than sharing on a common drive.

Steps to Install Maven with TestNg in Selenium
You should have Eclipse installed in your machines. Along with that, you need m2eclispe plug-in which you can download from Eclipse marketplace.
You can go to Eclipse marketplace and then search Maven and the first plug-in which will come, you can download that.
Let’s see how to create a Maven project.

  • Create a new Project by File -> New -> Other and then select Maven -> Maven project.
  • Click on Next and then you have to enter Artifact Id and Group Id. Group Id would be your Project Name and Artifact Id would be your Project folder name.
  • Select a template for your project. Select “Maven quikstart template”.
  • You will then get a WebDriver Test with a folder structure.
  • xml will be shown in the project structure. POM is the heart of the maven. In POM.xml project node you have to add following dependencies.

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.45.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
</dependencies>

  • This way, you can add dependencies in the POM.xml. You can search for dependency tag in Maven repository.
  • Create a TestNG class with name NewTest.xml and it will also be added to your project structure.
  • Now remember one thing that for running test through maven you need maven surefire plugin and along with testng.xml plugin for integrating with testng. Along with these two things, third plugin Maven compiler plugin is also required which is used for helping in compiling the code.

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>TestNG.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>

  • Now, you can go to Windows Path where pom.xml is placed. Open cmd there and fire commands.

1. mvn clean
2. mvn compile
3. 0mvn test // for all tests to be executed.
4. mvn -dtest // for a particular test to be executed.
Steps to Install Jenkins with Selenium
Let’s see how to configure Jenkins with Selenium so that client and all technical people would be able to handle a single server for all test results.
1. Click here and download correct package for your operating System. Then you can install Jenkins Unzip Jenkins to a specific folder and run its exe file.
2. When you are done with installation of Jenkins you have to fire a command in cmd to start your jenkins server.
java -jar jenkins.war
3. It will automatically host the server on 8080 port but if you don’t want it to run on 8080 port then you can specify the port number along with the command.
4. After that is done. You can visit https://localhost:8080 You can do the installation of necessary plugins. Then you can click on New Item and then select the Maven project.
5. Then you can click on Ok and a new job will be created with the name specified by you.
6. Now go to Manege Jenkins and then Configure Systems. Configure Maven and JDK there and go to Build Section and enter their full path of your pom.xml.
app testing
7. Now click on Apply. On the main page, click on “Build Now” link. Maven will automatically execute the test. After the build is done click on your project name.
8. In the left sticky bar you can see the execution history. You can click on the latest results to view the test results.
9. Even you cans schedule the test cases with Jenkins. You have to go to modify the configuration and there enter “Build Periodically” and enter the time in the manner like “0 23 * * *”. It will trigger everyday at 11 pm.
Conclusion
This way you can make your build process easier easy and can do continuous integration with Jenkins. This will increase the time efficiency and will help in better management of your test suite.

Recommended For you : 15 Top Selenium WebDriver Commands For Test Automation

Why the Need for Web Service Test Automation

Web service test automation solutions are the ones that help in testing and identifying whether a particular application communicates effectively and is able to access functions correctly from the web. These solutions also effectively help in confirming how a particular web service connected to them, behaves in different situations. In other words, this solution is an effective way to verify whether the services meet the terms of business logic and also deliver the desired output at the user’s end.
app testing
While it is well-known that web services provide flawless connection between two software applications over private intranets and the internet, the testing of these services is used to check the ways in which a single we service functions and managed load for a single client and balances the same with the increase in the number of users accessing it.
Web service testing is helpful in avoiding the delay in detection of errors, which, in turn, might lead to complex and costly repairs. When this process is automated, it gets easier to repeat tests as and when required. Therefore, using web services test automation is not only helpful in the development of sound and efficient web services development process but also in the assessment of their functionality, performance, and scalability.
Need of web services automation
While there can be numerous ways to conduct web services testing, but a typical one includes the following tasks:

  • Generating client or skeleton code for the web service.
  • Defining the required test inputs.
  • Imploring the web service using the client or skeleton code.
  • Generating client or skeleton code.
  • Response verification in terms of whether the actual response is similar to that of the expected outcome.

 Benefits of Web Service Test Automation
 Using web service testing automation can benefit the company in a number of ways. Some of these are as mentioned below: 

  1. Improved performance and reliability of SOA:

Service Oriented Architecture (SOA) is a set of services that communicate with each other. These services that are connected by web services, can either be a data transfer or a group of activities engaging in coordinating some other activity.
Using web service test automation tools can help in improving the performance and reliability of these SOAs. This is owing to their ability to communicate effectively and testing the ground on various measures.

  1. Eases testing:

Using a web service test automation tool helps in simplifying the process of testing web application. This is owing to their ability to effectively communicate with the web applications, which further adds on their ability to deliver the desired performance. Therefore, one can opt to use these tools for testing both SOA-based and REST API-based web services.

  1. Supports cloud environment

Cloud computing is a type of computing infrastructure and software model that gives its users access to shared pools of resources from any part of the world. This shared pool of resources can be computer networks, applications or servers and can be rapidly provided with minimal management effort, often over the Internet.
When a user is required to execute a test of web services that are available in a cloud environment, using a web service test automation tool makes it easier. Using this tool enables a faster and quicker testing.

  1. Simplifies testing over regression cycles

Regression testing cycle is a kind of software testing which is used to confirm whether software’s previous version performs in the same way like it did before the development of new version or interfacing with other software.
Web service automation helps in reducing the testing time and efforts it takes in testing a product over regression cycles.

  1. Ensures complete testing of product

 Using web service test automation vanishes the concept of testing one or some aspects of particular software. Instead, making use of this tool ensures a 100% functional test coverage of the same, hence, ensuring better performance.
It is, therefore, advisable to the companies to use this web service test automation. The reasons are multiple, from ease of use, reduced time to better performance.

Difference Between Selenium RC and Webdriver

Testing is an integral part of any product’s development. Therefore, it is important for every organization to have a stringent quality testing strategy and framework that helps it ensure the best quality of its products. While a number of software are already present in different frameworks in the market, Selenium is one of the most preferred one.
Difference Between Selenium RC and Webdriver
Selenium is defined as a portable software-testing framework that can be used for web applications. It can be used for authoring tests without the need to learn scripting language Selenium IDE and test domain-Selenese to write tests in a number of popular programming languages, including C#, Groovy, Java, Perl, PHP, Python, Ruby and Scala. These tests can used to execute against different-or latest web browsers.
A user can use selenium on Windows, Linux, and OS X platforms as well. It is an open-source software, released under the Apache 2.0 license and is available for free for downloading.

Selenium includes a number of components and each of these have a specific function to perform development of web application test automation. Some of the common components are Selenium IDE (integrated development environment), Selenium client API, Selenium RC (Remote Control), Selenium WebDriver and Selenium Grid.
Difference Between Selenium RC and Webdriver
 While it is true that Selenium WebDriver python test automation framework is a successor of Selenium RC, there are still a number of similarities as well as differences between the two. This article can help you develop a better understanding about the same and help you avoid any sort of confusion between the two.

  1. Browsers

Both these tools can be used on different browsers such as, Firefox, IE, Chrome, Safari, Opera and others.

  1. Recording and playback

Whether a user is using RC or WebDriver, it is possible for him/her to record as well as playback the execution of a test.

  1. Executing test script

While RC requires one to start server again before executing the test script, the same is not a mandate in case of WebDriver.

  1. Type of program

RC is a separate java program that allow a user execute HTML test suites. Whereas WebDriver is a programming interface which is available in multiple languages.

  1. Platform for interaction

RC server executes the test as JavaScript commands whereas WebDriver performs on Selenium commands and a browser.

  1. API

The API (Application Programming Interface) of RC is easy and small. But these contain a lot of redundancies and a lot of confusing commands. Various browsers interpret commands differently.
On the other hand, the API of WebDriver is large and a bit complex. These are also simple to comprehend and do not contain any sort of redundancy or confusing commands.

  1. Object-oriented

Selenium RC’s are not much object-oriented whereas Selenium WebDriver’s are completely object-oriented

  1. App testing

One cannot test any sort of iPhone or Android application on Selenium RC whereas the same can be done using WebDriver.

  1. XPath attachment

Selenium RC requires one to attach complete XPath whereas the same is not mandatory in case of WebDriver.

  1. Implementation of listeners

It is not possible to implant listeners in Selenium RC whereas one can do the same with a WebDriver.

  1. Execution speed

As compared to Selenium RC, WebDriver is faster in its execution as it is directly connected with the browser. The use of JavaScript program called Selenium Core slows down the Selenium RC’s speed.

  1. Syntax

While the syntax of RC is quite complex, the same is simple and easy to understand in case of WebDriver.
The basic purpose behind introducing Selenium WebDriver test automation framework in the market was to deal with the problem areas of Selenium RC as well as increase the scope of testing.

It is recommended to make use of Selenium WebDriver test automation framework for testing purposes however, the same depends on one’s choice as well the requirements.