Selenium is an open-source web-based functional and regression automation testing tool. Selenium automates browser. Selenium IDE, RC(Deprecated), WebDriver, and Grid are the components of the Selenium.
Selenium IDE has got one of the best features called Recording and Playback. We do not have to create scripts manually. there is a recording button available in IDE. Click on the record button and whatever we execute on the firefox browser, everything will be recorded in the tool. selenium stores the attribute of the Web Element of the individual action on the web pages like ID, Name, CSS, Xpath, and when we run the script it performs an operation on the web pages accordingly
Selenese is the language that is generally used to write test scripts in Selenium IDE. Selenese commands are stored in the Selenium Core library which is in-build of Selenium IDE
Locators are used to locating elements on the webpage. If you want to click, type or select any element on the webpage, we need to tell selenium to use a locator. Locators: id, name, xpath, cssSelector, linkText, partialLinkText, tagName and className
verify commands continues execution even if the text is not verified or the condition is false on the webpage. Execution will not be stopped.
Assert commands will stop execution in case of any error occurs or the condition is false. In both cases, errors will be reported in the log panel of IDE.
Webdriver is an interface that implements different classes like FirefoxDriver, ChromeDriver, InternetExplorerDriver etc...It is an interface helping us to automate websites. It helps us to make our tests easier. It is a collection of open-source APIs which are used to automate the testing of websites.
There is a findElement method from WebElement interface which has a constructor named By class and By class have static methods id, name, xpath, cssSelector, linkText, partialLinkText etc... Example: driver.findElement(By.id("xyz11")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); Where driver is a reference of WebDriver interface. If any webpage takes a long time to load, driver will wait for a maximum of 20 seconds. We can also define time units like minutes, hours, seconds, milliseconds, microseconds, days, etc..
We will write below mentioned line after defining webdriver. driver.manage().window().maximize();
WebElement is an interface that accesses most commonly used methods like click, sendKeys, getText, isDiplayed, isEnabled, isSelected etc..
There is a Select class which has a WebElement as a constructor. We will pass the webelement of the dropdown list as a constructor. We can use selectByVisibleText, selectByIndex, selectByValue methods to select the specific text from the drop down list. Example: Select sel = new Select(driver.findElement(By.name("country"))); sel.selectByVisibleText("India");
Close will close the current window you are currently dealing with. Quit will close all browser windows opened by WebDriver during execution.
There are two approaches in order to handle multiple elements.
Approach 1:
Let's say we have a group of links which are categorized in a division or table. So first we will take WebElement of the Division where our links are grouped together. Then We will use findElements method with the locator "tagName" and that will return List. Example: WebElement catDiv = driver.findElement(By.xpath("//*[@id='columnLeft']/div[1]/div[2]")); List catLinks = catDiv.findElements(By.tagName("a"));
Approach 2:
Create custom xpaths that will point to all web elements on the page and we can directly use findElements method to store elements in a list.
They both are methods of SearchContext interface. SearchContext is the super interface of the WebDriver. findElement returns WebElement and it mainly deals with the single elements. findElements returns List and it mainly deals with the multiple elements of the same group.
Example: WebElement catDiv = driver.findElement(By.xpath("//*[@id='columnLeft']/div[1]/div[2]")); List catLinks = driver.findElements(By.tagName("a"));
To navigate from one page to the previous page: driver.navigate().back(); To navigate from one page to the next page: driver.navigate().forward(); To refresh the current page: driver.navigate().refresh();
We can identify all the links by its tag name as anchor tag “a”. So our code will be
List
By looking at the above code, driver will find all the elements having tag as “a” on the page and all weblements will be stored in the List.
We can print all the text of web elements by defining them in a loop.
for(WebElement element: allWebPageLinks)
{
      System.out.println(element.getText());
}
There are multiple ways to check if frames are present or not.
We can write xpath in a different ways :
   1. //iframes
   2. driver.findElements(By.tagName("iframe"));
We can store all webelements of frames in the list and access it.
WebElement frameWindow = driver.findElement(By.xpath("Value of Xpath"));
driver.switchTo().frame(frameWindow);
Line 1: We are defining WebElement that is pointing to the frame on the webpage
Line 2: We are switching to that specific frame and now we can access all elements inside it.
Let’s assume you are already switched to frame and you want to come out from the frame then you can write below mentioned code.
driver.switchTo().defaultContent();
We can simply check the source code of the webpage and if that element is having an attribute called readonly and if it is set to true then the field is non-editable else it is editable. We can check that with the help of the getAttribute method of the WebElement interface.
String checkField = driver.findElement(By.xpath("locator")).getAttribute("readonly");
System.out.println(checkField);
In the above code, if checkField is true then the field is non-editable.
The main difference between the error and an exception is that we can't handle an error. It termi-nates the program but exceptions can be handled. We can handle the exception by implementing try/catch concept.
Examples:
Errors:-> StackOverFlow, OutOfMemory
Exceptions:-> ClassNotFound, NoSuchMethod, IndexOutOfBounds, NullPointer
We can check if the element is present or not by using isDisplayed method of WebElement. If the method returns true then the element is present else it is not present. If the element is not present then selenium throws an exception and we can handle the exception by implementing try/catch concept.
@BeforeSuite: The annotated method will be run before all tests in the suite.
@AfterSuite: The annotated method will be run after all tests in the suite.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the < test > tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the < test > tag have run.@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
There are different predefined assertions methods available in testNG. Assertions helps us to verify the condition of the test.
1. assertTrue(condition, message)
2. assertTrue(condition)
3. assertFalse(condition, message)
4. assertFalse(condition)
5. assertEqual(String actual, String expected, String message)
6. assertEqual(String actual, String expected)
7. assertEqual(boolean actual, boolean expected)
8. assertNull(Object obj, String message)
9. assertNull(Object)
There are few more assertions are available. However, we use only few of them during realtime execution.
Assert is a class developed by the testNG team. It is generally used to check the conditions in the program normally we call it a checkpoint.
Hard Assert: Hard Assert throws an exception immediately if an assert statement fails during the execution and stops the current code which is written in the same @Test method and it will contin-ue with the next @Test Test.
Assert.fail() is an example of Hard Assert.
Soft Assert: Soft Assert does not throw an exception during the execution of the @Test method. It collects all errors during the execution of the @Test method. It will execute the next statement even if the assert statement fails.
We can set the priority of the different @Test by using priority attribute.
package module1;
import org.testng.annotations.Test;
public class PriorityTestNG {
@Test(priority=1)
public void positiveRegisterTest() {
System.out.println("Positive Register Test");
}
@Test(priority=2)
public void negativeRegisterTest() {
System.out.println("Negative Register Test");
}
}
If priority is not set, then all @Test execute in alphabetical order.
Yes. We can disable particular test case by defining parameter enabled = false for a specific @Test method.
@Test(enabled=false)
public void searchTest() {
System.out.println("Search Test");
}
If there are more than one @Test annotation methods are created in one class and one @Test is defined with Priority=1 parameter and second @Test is defined without priority, then @Test without priority will be executed first and then @Test method with priority will be executed.
We can check if the element is displayed or not by using isDisplayed method of WebElement inter-face. If the method returns true then the element is displayed on the webpage else it is not dis-played. If the element is not displayed then method will not return false, selenium throws an excep-tion and we can handle the exception by implementing try/catch concept.
We can get the text of any web element by using getText() method of the WebElement interface.
String elementText = driver.findElement(By.id("XYZ")).getText();
We can check if any radio button is selected or not by using isSelected() method of WebElement interface.
boolean checkSelection = driver.findElement(By.id("XYZ")).isSelected();
In the above code, if radio button is selected then true will be stored in checkSelection else false will be stored.
Some of elements on the webpage may take long time to load the webpage. We can implement wait by below mentioned two lines.
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Change Password")));
In the above code, selenium will wait for 5 seconds for the Change Password link to be present on the page.
Clear is the method of WebElement interface. If a text box is having specific pre-defined value in the text box and if we want to clear it before we type any new text, we can use clear method.
Example: driver.findElement(By.name("email")).clear();
driver.navigate().back(); //This will take user to the previous page.
driver.navigate().forward(); //This will take user to the next page.
With the help of driver.navigate().refresh(); , selenium refresh the webpage
With the help of the getCurrentUrl() method, we can get URL of the current page.
String currentURL = driver.getCurrentUrl();
We can handle window based pop up by switching to Alert interface.
driver.switchTo().alert().accept();
driver will click on OK/YES button present on the alert window. It returns true in the javascript code.
driver.switchTo().alert().dismiss();
driver will click on CANCEL/NO button present on the alert window. It returns true in the javascript code.
In order to drag and drop, we need to create an object of Actions class. There are two approaches for dragging specific object/element.
1. Drag element and drop at specific x y coardinates.
WebElement object = driver.findElement(By.id("ID of the element"));
Actions act = new Actions(driver);
act.dragAndDropBy(object, 100, 50).build().perform();
2. Drag the element and drop it at another element
WebElement source = driver.findElement(By.id("ID of the element"));
WebElement destination = driver.findElement(By.id("ID of the element"));
Actions act = new Actions(driver);
act.dragAndDrop(source, destination).build().perform();
When we use driver.close(), the driver will close the current window that the user is currently work-ing on, and driver.quit() will close all windows which are opened and accessed by Webdriver.
For Google Chrome:
System.setProperty("webdriver.chrome.driver", "/Users/tanmayshah/chromedriver");
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);
For Firefox:
System.setProperty("webdriver.gecko.driver", "/Users/tanmayshah/geckodriver");
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
WebDriver driver = new FirefoxDriver(options);
In order to get the tooltip value from the text box, we will use getAttribute("title") method of WebElement interface.
Example: String tooltipText = driver.findElement(By.xpath("xpath")).getAttribute ("title"));
contextClick is the method of Actions class which is used to right click on any element.
Example:
Actions act = new Actions(driver);
WebElement signInBtn = driver.findElement(By.id("id of the element"));
action.contextClick(element).perform();
In order to get the typed value from the text box, we will use getAttribute("value") method of WebElement interface.
Example: String typedText = driver.findElement(By.name("email_address")).getAttribute ("value"));
doubleClick is the method of Actions class which is used to double click on any element.
Example:
Actions act = new Actions(driver);
WebElement signInBtn = driver.findElement(By.id("id of the element"));
action.doubleClick(element).perform();
All classes of the exceptions are defined under org.openqa.selenium package. Below are some of them.
NoSuchElementException - When no element could be located from the locator provided.
ElementNotVisibleException - When the element is present in the dom but is not visible.
NoAlertPresentException - When we try to switch to an alert, but the targeted alert is not present.
NoSuchFrameException - When we try to switch to a frame, but the targeted frame is not present.
NoSuchWindowException - When we try to switch to a window, but the targeted window is not present.
UnexpectedAlertPresentException - When an unexpected alert blocks the normal interaction of the driver.
TimeoutException - When a command execution gets a timeout.
InvalidElementStateException - When the state of an element is not appropriate for the desired action.
NoSuchAttributeException - When we are trying to fetch an attribute's value, but the attribute is not correct
WebDriverException - When there is some issue with the driver instance preventing it from getting launched.
With the help of getCookies() method, Selenium stores all cookies in the Set.
Example:
Set< Cookie > cookies = driver.manage().getCookies();
for(Cookie c:cookies)
{
System.out.println("Cookie Domain->"+c.getDomain());
System.out.println("Cookie Name->"+c.getName());
System.out.println("Cookie Value->"+c.getValue());
System.out.println("Cookie Path->"+c.getPath());
}
There are different methods available in Cookie class that can help tester to validate session information.
getDomain(), getName(), getValue(), getPath() etc..
We can use getWindowHandle() and getWindowHandles() method in order to get all window ID's of the pages accessed by webdriver.
Set< String > windowID = driver.getWindowHandles();
With the help of below line, we will iterate all child windows.
Iterator
By writing below line, id of the window will be stored in the wID variable.
wID = iter.next();
driver will be switched to the another window by executing below line.
driver.switchTo().window(wID);
get()-> get method is used to to navigate url and will wait untill page will be loaded.
navigate()-> navigate method is used to navigate to url and will not wait page to load. It also maintains the history of the browser, cookies to navigate back, forward or refresh the webpage.
getPageSource is the method of WebDriver. By using getPageSource(), it will get the html source code of the loaded page.
String pageSourceCode = driver.getPageSource();
If link or any other web element is not accessible by selenium webdriver, then we can try with JavaScriptExecutor. JavaScriptExecutor is an interface that is used to execute javascript.
We need to create a reference first by writing below line.
JavascriptExecutor js = (JavascriptExecutor) driver;
There is a executeScript method used to execute the script.
js.executeScript(script, args);
To click on any element:
js.executeScript("document.getElementByID('element id').click();");
To type any value in the text box:
js.executeScript("document.getElementByID('element id ').value='Hello';");
There are few more operations we can handle using JavaScriptExecutor.
To capture a screenshot in Selenium, we can use interface called TakesScreenshot.
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs“.
FileUtils.copyFile(file, new File("Location where file needs to be stored"));
Captured file will be copied to the specified location.
Object of Actions class is required in order to support mouseover event.
WebElement mainMenu = driver.findElement(By.xpath("xpath"));
WebElement subMenu = driver.findElement(By.xpath("xpath"));
Actions act = new Actions(driver);
act.moveToElement(mainMenu).build().perform();
subMenu.click();