Wednesday, 28 September 2022

Selenium Interview Questions



1.How to perform back,forward and refresh action in selenium?
driver.navigate().back()
driver.navigate().forward()
driver.navigate().refresh()


2. What is the return type of findelements?
List of elements with similar property

3. What will happen if no webelement is found for findelements?

It will return an empty list

4. What will happen if no webelement is found for findelement?
It will give error as :NoSuchElementException

5. How to select value from dropdown in selenium?

Using select class as below
Select technology = new Select(driver.findElement(By.xpath("//select[@id='effectTypes']")));
technology.selectByVisibleText("Drop");

6. What are the methods provided in selenium to select from dropdown?

selectByVisibleText()
selectByValue()
selectByIndex()
7. How to fetch text from UI in selenium?

gettext()
getAttribute("propertyname")
8. How to get current url,title and page source?

driver.getCurrentUrl();
driver.getTitle();
driver.getPageSource();
9. How to clear text using selenium?

clear() — method is used to clear text from the text area
driver.findElement(By.xpath(“//input[@placeholder=’Username’]”)).clear();

10. How to do Browser Initialization for all types of browser?

• Firefox
WebDriver driver = new FirefoxDriver();
• Chrome
WebDriver driver = new ChromeDriver();
• Internet Explorer
WebDriver driver = new InternetExplorerDriver();
• Safari Driver
WebDriver driver = new SafariDriver();




11. How to handle alerts and popups in selenium?• driver.switchTO().alert.accept() — to accept the alert box

• driver.switchTO().alert.dismiss() — to cancel the alert box

12. How to retrive alert pop up message in selenium?

• driver.switchTO().alert.getText() — to retrieve the alert message

13. How to send data to alert box in Selenium?

• driver.switchTO().alert.sendKeys(“Text”) — to send data to the alert box


14. How to switch frames in selenium?

• driver.switchTo.frame(int frameNumber) — mentioning the frame index number, the Driver will switch to that specific frame
• driver.switchTo.frame(string frameNameOrID) — mentioning the frame element or ID, the Driver will switch to that specific frame

• driver.switchTo.frame(WebElement frameElement) — mentioning the frame web element, the Driver will switch to that specific frame

15. How to switch back to main window in frames?

• driver.switchTo().defaultContent() — Switching back to the main window

16. How to handle multiple windows and tabs in Selenium?
• getWindowHandle() — used to retrieve the handle of the current page (a unique identifier)

• getWindowHandles() — used to retrieve a set of handles of the all the pages available

17. How to switch between windows and tabs?

• driver.switchTo().window(“windowName/handle”) — switch to a window

18. How to close the cureent browser window?

• driver.close() — closes the current browser window

19. How to handle Implicit wait?
Used to wait for a certain amount of time before throwing an exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

20. How to handle Explicit wait?
Used to wait until a certain condition occurs before executing the code.
WebDriverWait wait = new WebDriverWait(driver,30);

wait.until(ExpectedConditions.presenceOfElementLocated(By.name("login")));
21. What are the element validation methods in selenium?
• isEnabled() — determines if an element is enabled or not, returns a boolean.
• isSelected() — determines if an element is selected or not, returns a boolean.
• isDisplayed() — determines if an element is displayed or not, returns a boolean.

22. How to handle proxy in selenium for chrome?

ChromeOptions options = new ChromeOptions();// Create object Proxy class - Approach 1
Proxy proxy = new Proxy();
proxy.setHttpProxy("username:password.myhttpproxy:3337");
options.setCapability("proxy", proxy);
ChromeDriver driver = new ChromeDriver(options);

23. How to set the size of the window in selenium?

driver.manage().window().setSize(new Dimension(1024, 768));

24. How to fetch the size of window in Selenium?

Dimension size = driver.manage().window().getSize();
int width = size.getWidth();
int height = size.getHeight();

25. How to maximize the window in selenium?

driver.manage().window().maximize();

26. How to drag and drop from source to destination?

WebElement source = driver.findElement(By.xpath("//div[@id='draggable']"));
WebElement destination = driver.findElement(By.xpath("//div[@id='droppable']"));
Actions builder = new Actions(driver);
builder.dragAndDrop(source,destination);

27. How to perform keyboard actions in selenium?

By using Robot class as below:
Robot robo = new Robot();
robo.keyPress(KeyEvent.VK_ENTER);

28. How to get all cookies and with name of the cookie?

driver.manage().getCookies();
driver.manage().getCookieNamed("APISID");

29. How to delete all cookies and with name of the cookie?

driver.manage().deleteCookieNamed("APISID");
driver.manage().deleteAllCookies();

30. How to add a cookie?

Cookie cookie1 = new Cookie("test2", "cookie2");

driver.manage().addCookie(cookie1);




31. How to rerun failed test cases in Selenium using TestNG?
Click here to answer

32. What approach to take if clear() method is not working on a textbox?

sendKeys(Keys.chord(Keys.CONTROL,"a",Keys.DELETE));

33. How to run test case in parallel for multiple browsers?

<suite name="Automation Test Suite " parallel="tests" thread-count="2">
<test name="Automation Test CasesChrome">
<classes>
<class name="com.task.automation.testtwo.testone"/>
</classes>
</test>
<test name="Automation Test Casesfirefox">
<classes>
<class name="com.task.automation.testtwo.testfirefox"/>
</classes>
</test>
</suite>

34. Create a common method for Explicit wait to check element is visible or not?

public void waitForElementVisible(WebElement element, long timeout) {

try {
new WebDriverWait(driver, timeout).until(ExpectedConditions.visibilityOf(element));
} catch (ElementNotVisibleException e) {
Reporter.log(element.toString() + "is not visible");
Reporter.log(e.getStackTrace().toString());
}

}
Top API Interview Question 11-20

35. How to prepare automation test estimation ?

Click here for answer

36. How to launch batch file from Selenium WebDriver?

Process batch = Runtime.getRuntime.exec("path of the batch file");

37. How to run selenium test from command line?

java -classpath ".;selenium-server-standalone-2.33.0.jar" SampleClass

38. What is the name of the super interface of the Webdriver?

Ans: SearchContext.

39. Explain some of the strategy you have followed while using xpath?

Click here for answer

40. How to execute the testng test suite from the command line?

Ans: java -cp “C:\AutomationReinvented\testng \lib\*;C:\AutomationReinvented\testng\bin” org.testng.TestNG testng.xml




41. What’s the difference between soft and hard asserts?


A soft assert will run the test and not throw an exception if the assert failed, while a hard assert will throw the exception immediately, and then continue with the testing process.



@Test
public void softAssertion(){
SoftAssert softAssertion= new SoftAssert();
System.out.println("softAssert");
softAssertion.assertTrue(false);
softAssertion.assertAll();

}

@Test
public void hardAssertion(){
System.out.println("hardAssert");
Assert.assertTrue(false);
System.out.println("hardAssert");
}

Soft Assertions are the type of assertions that do not throw an exception when an assertion fails and continue with the next step after the assert statement. This is used when the test requires multiple assertions to be executed and we want all of the assertions/codes to be executed before failing/skipping the tests.

Hard Assert is a type of TestNG assetion which throws Exception Immediately if the assert statement fails and move to the next testcase and if there is any code in the current test case after assert statement it will not execute that statement.

42. How would you upload a file via Selenium Webdriver? Know About Kubernetes


Let we have a button as "Choose File", so first need to identify this element as below


@FindBy(xpath="//span[contains(text(),'Activate')]")
public WebElement chooseFile;



Use sendkeys with the file path that you want to upload:

chooseFile.sendKeys("C:\\filetoupload")

43. What are the parameters do you have to meet for Selenium to pass a test?


There are four conditions (parameters) for Selenium to pass a test, as below:

URL, host, browser and port number.

44. Have you worked on invocation count/thread count or any advanced TestNG annotation, if Yes then can you explain?

alwaysRun
If set to true, this test method will always be run even if it depends on a method that failed.

dependsOnMethods
The list of methods this method depends on.

@test:
Marks a class or a method as part of the test.
Description:
The description for this method. It is important to give a small information about the test case.



Enabled:
Whether methods on this class/method are enabled.
invocationCount
The number of times this method should get invoked.

threadPoolSize
The size of the thread pool for this method. The method will be invoked from multiple threads as specified by invocationCount.


Note: this attribute is ignored if invocationCount is not specified

timeOut
The maximum number of milliseconds this test should take.
expectedExceptions
The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.




45. Tell me two things that you can't automate using Selenium?


Captcha and Barcodes


46. Explain some of the keywords that has been used in your project for BDD approach?
Scenario outline:


The Scenario Outline keyword can be used to run the same Scenario multiple times, with different combinations of values.
Background:

Sometimes you’ll find yourself repeating the same Given steps in all of the scenarios in a feature.
Since it is repeated in every scenario, this is an indication that those steps are not essential to describe the scenarios. You can literally move such Given steps to the background, by grouping them under a Background section.

Monochrome:


Display console output in readable way

Glue:


it helps Cucumber to locate theStep Definition file.Whenever Cucumber encounters a Step, it looks for a Step Definition inside all the files present in the folder mentioned in Glue Option.
Feature:

The purpose of the Feature keyword is to provide a high-level description of a software feature, and to group related scenarios.The first primary keyword in a Gherkin document must always be Feature, followed by a : and a short text that describes the feature.
plugin:


plugin Option is used to specify different formatting options for the output reports.

Format:


It will define the format of the reports. Options are pretty,html,json,junit.
Note – Format option is deprecated . Use Plugin in place of that.
RunWith:


This is a JUnit annotation that specifies which runner it has to use to execute this class

CucumberOptions:


This annotation provides some important information which will be used to run your cucumber feature file.

Given:


It is for pre condition

When:

Test action that will get executed

Then:


It defines the expected result.
Add:

Add conditions to step
But:


It is used to add negative type comments
Strict:

with true as opted value, It will fail execution if any undefined or pending steps found.

dryRun: Check if all steps have step definition tag:


The tags can be used when specifying what tests to run through any of the running mechanism.
@RunWith(Cucumber.class)
@CucumberOptions(
features = “src/test/“,
tags ={“@Web“},... )
Cucumber can exclude scenarios with a particular tag by inserting the tilde character before the tag.
For the following command will run all Scenarios without the UI tag.
@RunWith(Cucumber.class)
@CucumberOptions(
features = “src/test/features“,
tags ={“~@UI“},... )

47. What will happen if you run this command. driver.get(“www.google.com”) ?


As the given URL doesn’t contain http or https prefix so it will throw an exception.

So, it is required to pass HTTP or HTTPS protocol within driver.get() method.

driver.get(“https://www.google.com”);




48. What is Recovery Scenario in Selenium WebDriver?


Recovery Scenarios is done by using “Try Catch” block within Selenium WebDriver :.

try{
driver.get(“https://www.google.com“);
}
catch (Exception e){

e.printStackTrace();


}

49. Which Source code management tool you have used and tell me some of the basic commands that you have used?

Git

50. Have you worked on database side for fetching data to validate in selenium tests, if Yes then can you tell me some of the basic queries that you have used in day to day work?


SQL Queries




71. What is default time for implicit and explicit wait?

Implicit wait default time is zero.
Explicit wait default time is 500 ms

72. What is remote WebDriver client?

ChromeOptions chromeOptions = new ChromeOptions();

chromeOptions.setCapability("browserVersion", "67");

chromeOptions.setCapability("platformName", "Windows XP");

WebDriver driver = new RemoteWebDriver(new URL("http://www.example.com"), chromeOptions);

driver.get("http://www.google.com");

driver.quit();




73. What is the use of Driver in Selenium?



Responsible for controlling the actual browser. Most drivers are created by the browser vendors themselves. Drivers are generally executable modules that run on the system with the browser itself, not on the system executing the test suite.

74.What are the new features in Selenium 4? VERY IMP

Click Here For Detail Answer


75. Explain some of the strategy to handle CAPTCHA?

There are two primary strategies to get around CAPTCHA checks:Disable CAPTCHAs in your test environment
Add a hook to allow tests to bypass the CAPTCHA

76. What is page load strategy in Selenium?

Click Here For Answer
77. What is Relative Locators?


Selenium 4 brings Relative Locators which are previously called as Friendly Locators. This functionality was added to help you locate elements that are nearby other elements. The Available Relative Locators are:above
below
toLeftOf
toRightOf
near
78. What is the use of withTagName()?


indElement method now accepts a new method withTagName() which returns a RelativeLocator.


79. How to perform parallel test with cross browser using docker?


Click Here For Answer With Code



80.How to create a custom profile ?




FirefoxProfile profile = new FirefoxProfile();

FirefoxOptions options = new FirefoxOptions();

options.setProfile(profile);

driver = new RemoteWebDriver(options);



BONUS.How do you achieve synchronization in WebDriver?


We can achieve synchronization either by using Static Wait or Dynamic Wait.
Static wait : Thread.sleep(): not good practice to use static wait
Dynamic wait: This can be achieved by using Implicit wait, Explicit Wait, Fluent Wait

No comments:

Post a Comment