Selenium Interview Questions Answers

1. 1. What is Selenium and the different components of Selenium?


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.

2. How does Selenium IDE Work?


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

3. What is Selenese?


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

4. What are the locators Selenium?


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

5. What is the difference between verify and assert command in Selenium IDE?


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.

6. What is Webdriver?


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.

7. How to find HTML elements using WebDriver?


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();

8. How to define implicitlywait in WebDriver?


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

9. How to maximize browser window using Webdriver?


We will write below mentioned line after defining webdriver. driver.manage().window().maximize();

10. What is WebElement in Webdriver?


WebElement is an interface that accesses most commonly used methods like click, sendKeys, getText, isDiplayed, isEnabled, isSelected etc..

11. How to select a value from a drop-down list?


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");

12. Difference between close and quit.


Close will close the current window you are currently dealing with. Quit will close all browser windows opened by WebDriver during execution.

13. How to handle multiple elements on the webpage?


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.

14. Difference between findElement and findElements.


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"));

15. How to navigate from one page to the previous page or the next page?


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();

16. How to print all the links on the webpage?


We can identify all the links by its tag name as anchor tag “a”. So our code will be
List allWebPageLinks = driver.findElements(By.tagName("a"));
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());
}

17. How to check if frames are present on the webpage or not?


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.

18. How to access specific element if it is inside the frame?


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.

19. How to come out from the frame?


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();

20. How do we check if particular element is editable or not?


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.

21. What is the difference between error and exception?


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

22. How to check if an element is present or not?


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.

23. Explain different annotations available in TestNG.


@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 [email protected]: 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.

24. How to assert text using TestNG and what are the common testing annotations?


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.

25. Difference between SoftAssert and Hard Assert in TestNG?


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.

26. How to set priority in test method using TestNG?


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.

26. How to execute test cases parallel using TestNG?


27. Can we disable particular test case using TestNG?


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");

}

28. If one method is defined with priority and another one is defined without priority then which method will be picked first for execution?


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.

29. How to check if particular element is displayed or not?


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.

30. How do we get the text of any element on the webpage?


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();

31. How to check if radio button is selected or not?


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.

32. What is explicitlywait in Selenium?


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.

33. What is the use of clear method?


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();

34. How to navigate to previous page and next page?


driver.navigate().back(); //This will take user to the previous page.

driver.navigate().forward(); //This will take user to the next page.

35. Can we refresh webpage using Selenium Webdriver?


With the help of driver.navigate().refresh(); , selenium refresh the webpage

36. How do we get the current url of the webpage?


With the help of the getCurrentUrl() method, we can get URL of the current page.

String currentURL = driver.getCurrentUrl();

37. How to handle window based pop up using Selenium ?


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.

38. Drag and drop handling using Webdriver?


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();

39. Difference between close and quit methods?


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.

40. How to run script using headless browser?


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);