Anh Tester chia sẻ đến các bạn 100 câu hỏi chọn lọc về Selenium. Mình lấy từ tài liệu tiếng Anh và muốn giữ nguyên bản để các bạn dịch ra và hiểu cho chuẩn hơn mình dịch sai ý nữa hehe.
Và dưới đây là Anh Tester chọn ra 10 câu hỏi cần quan tâm cho các bạn:
Các phần chính trong 100 câu về Selenium gồm:
Ans. Selenium is a robust test automation suite that is used for automating web-based applications. It supports multiple browsers, programming languages, and platforms.
Ans. Selenium comes in four forms-
Ans. Following are the advantages of Selenium-
Ans. Following are the limitations of Selenium-
Ans. Some commonly used browsers supported by Selenium are-
Ans. No. Selenium WebDriver uses the browser’s native method to automate the web applications. So, there is no support for testing web services using Selenium WebDriver.
Ans. The different locators in Selenium are-
Id
XPath
CSS selector
className
tagName
name
link text
partialLinkText
Ans. In order to locate web elements, we can use the Developer tool and plugins like Firebug.
The developer tool can be launched by pressing F12 on the browser. Users can easily hover over any element and find its different HTML properties.
Firebug is a plugin of Firefox that provides various development tools for debugging applications. From an automation perspective, Firebug is used specifically for inspecting web elements in order to find their attributes like id, class, name, etc. in different locators.
Ans. Xpath or XML path is a query language that is used for selecting nodes from XML documents. Also, it is one of the locators supported by Selenium Webdriver.
Ans. An absolute XPath is a way of locating an element using an XML expression, beginning from the root node i.e. HTML node in the case of web pages.
The main disadvantage of absolute XPath is that even if there is a slight change in the UI or any element then also whole XPath will fail.
Example – html/body/div/div[2]/div/div/div/div[1]/div/input
Ans. A relative XPath is a way of locating an element using an XML expression, starting from anywhere in the HTML document.
In this way, there are different ways of creating robust relative XPaths that are unaffected by changes in other UI elements.
Example – //input[@id=’username’]
Ans. In XPath, a single slash is used for creating absolute XPaths, beginning from the root node. Whereas double slash is used for creating relative XPaths.
Ans. Using contains() method we can locate an element by partially matching its attribute’s value. This is particularly helpful in scenarios where the attributes have dynamic values with a certain constant part.
xPath expression = //*[contains(@name,'user')]
Basically, the above statement will match all the values of the name attribute containing the word ‘user’ in them.
Ans. Using the text()
method –
xPathExpression = //*[text()='username']
Ans. Using ‘/..’ after the XPath expression of the child element, we can move to the parent of an element.
For example, the locator //div[@id=”childId”]/..
will move to the parent of the div element with id value as ‘childId’.
Ans. Basically, there are two ways of navigating to the nth element using XPath-
Ans. By using .className in the CSS locator, we can select all the elements belonging to a particular class e.g. ‘.red’ will select all elements having class ‘red’.
Ans. By using #idValue in the CSS locator, we can select all the elements belonging to a particular class e.g. ‘#userId’ will select the element having an id – userId.
Ans. Using [attribute=value] in the CSS locator, we can select all the elements belonging to a particular class e.g. ‘[type=small]’ will select the element having an attribute type of value ‘small’.
Ans. Using :nth-child(n) in the CSS locator, we can move to the nth child element e.g. div:nth-child(2) will locate the 2nd div element of its parent.
Ans. The fundamental difference between XPath and CSS selector is – using XPaths we can traverse up in the document i.e. we can move to parent elements. Whereas using the CSS selector, we can only move downwards in the document.
Ans. By creating an instance of the desired browser driver e.g. below command will initialize the Firefox browser.
WebDriver driver = new FirefoxDriver();
Ans. Both driver.get(“URL”)
and driver.navigate().to(“URL”)
commands are used to navigate to a URL passed as a parameter.
There is a minor difference between the two commands-
driver.navigate()
allows moving back and forward in browser history with the help of driver.navigate().forward() and driver.navigate().back()
commands.Ans. With the help of sendKeys() method we can type text in a textbox-
WebElement searchTextBox = driver.findElement(By.id("srch"));
searchTextBox.sendKeys("searchTerm");
Ans. In order to delete the text written in a textbox, we can use the clear() method.
driver.findElement(By.id("elementLocator")).clear();
Ans. The same click()
the method used for clicking buttons or radio buttons can be used for checking the checkbox as well.
Ans. Using the submit()
method we can submit a form in selenium.
driver.findElement(By.id("form1")).submit();
Also, the click()
method can be used for the same purpose.
Ans. The difference between close and quit commands is-driver.close()
– Used to close the current browser having a focus.driver.quit()
– Used to close all the browser instances.
Ans. Selenium has driver.getWindowHandles() and driver.switchTo().window(“{windowHandleName}”) commands to work with multiple windows.
The getWindowHandles() command returns a list of ids corresponding to each window. If we pass a particular window handle to the driver.switchTo().window(“{windowHandleName}”) command then we can switch control/focus to that particular window.
for (String windowHandle : driver.getWindowHandles()){
driver.switchTo().window(handle);
}
Ans. The driver.getWindowHandle()
returns a handle of the current window (a single unique identifier).
Whereas driver.getWindowHandles()
returns a set of handles of all the windows available.
Ans. The driver.switchTo() commands can be used for switching to a particular iframe.
driver.switchTo().frame("{frameIndex/frameId/frameName}");
For locating a frame, we can either use the index (starting from 0), its name, or its Id.
Ans. Yes, using driver.navigate().back()
and driver.navigate().forward()
commands, we can move backward and forward in a browser.
Ans. There a multiple ways to refresh a page in Selenium-
driver.navigate().refresh()
command.sendKeys(Keys.F5)
on any textbox on the webpage.driver.getCurrentUrl()
.driver.navigate().to(“URL”)
on the current URL or driver.navigate().to(driver.getCurrentUrl());
Ans. We can maximize the browser window using the following command-
driver.manage().window().maximize();
Ans. Using the getText()
method we can fetch the text over an element.
String text = driver.findElement("elementLocator").getText();
Ans. Using getAttribute(“{attributeName}”) method, we can find the value of different attributes of an element e.g.-
String valueAttribute = driver.findElement(By.id("locator")).getAttribute("value");
Ans. Using deleteAllCookies()
method.
driver.manage().deleteAllCookies();
Ans. An implicit wait is a type of wait that waits for a specified time while locating an element before throwing NoSuchElementException. By default, Selenium tries to find web elements immediately when required without any wait. So, it is good to use implicit wait. This wait is applied to all the elements of the current driver instance.
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Ans. An explicit wait is a type of wait that is applied to a particular web element until the expected condition specified is met.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));
It is advisable to use explicit waits over implicit waits because higher timeout value of implicit wait (set for handling only some of the elements) gets applied to all the web elements. Thus increasing the overall execution time of the script. On the other hand, we can apply different timeouts to the different elements in case of explicit waits.
Ans. Some of the commonly used expected conditions of an element that can be used with explicit waits are-
Ans. A fluent wait is a type of wait in which we can also specify polling interval (the time intervals after which driver will try to find the elements when not located) along with the maximum timeout value.
Wait wait = new FluentWait(driver)
.withTimeout(20, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement textBox = wait.until(new Function<webdriver,webElement>()
{
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("textBoxId"));
}
});
Ans. The different keyboard operations that can be performed in Selenium are-
Ans. The different mouse events supported in Selenium are-
Ans. Code to double click an element-
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.doubleClick(element).perform();
Ans. Code to right-click an element in selenium-
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.contextClick(element).perform();
Ans. Code to mouse hover over an element-
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.moveToElement(element).perform();
Ans. In order to fetch the current page URL, we can use the getCurrentURL() command.
driver.getCurrentUrl();
Ans. Using driver.getTitle()
command, we can fetch the page title in Selenium. This method returns a string containing the title of the webpage.
Ans. Using the driver.getPageSource()
command, we can fetch the page source in selenium. This method returns a string containing the page source.
Ans. Tooltips web elements have an attribute of type ‘title’. By fetching the value of the ‘title’ attribute, we can verify the tooltip text in selenium.
String toolTipText = element.getAttribute("title");
Ans. Using linkText() and partialLinkText() methods, we can locate a link. The difference between the two is – linkText() matches the complete string passed as a parameter to the link texts. Whereas partialLinkText() only matches the string parameter partially.
WebElement link1 = driver.findElement(By.linkText("artOfTesting"));
WebElement link2 = driver.findElement(By.partialLinkText("artOf"));
Ans. Desired capabilities are a set of key-value pairs that are used for storing or configuring browser-specific properties. For example – the browser’s version, platform, etc in the browser instances.
Ans. All the links are of anchor tag ‘a’. So by locating elements of tagName ‘a’ we can find all the links on a webpage.
List<WebElement> links = driver.findElements(By.tagName("a"));
Ans. Some of the commonly seen exceptions in Selenium are-
Ans. In order to take screenshots in Selenium, we can use the getScreenshotAs method of the TakesScreenshot interface.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\AnhTester.jpg"));
Ans. Using Select class-
Select countriesDropDown = new Select(driver.findElement(By.id("countries")));
dropdown.selectByVisibleText("India");
//or using index of the option starting from 0
dropdown.selectByIndex(1);
//or using its value attribute =
dropdown.selectByValue("Ind");
Ans. Using is Selected() method, we can check the state of a dropdown’s option.
Select countriesDropDown = new Select(driver.findElement(By.id("countries")));
dropdown.selectByVisibleText("VietNam");
//returns true or false value
System.out.println(driver.findElement(By.id("vietnam")).isSelected());
Ans. Using the isDisplayed() method we can check if an element is getting displayed on a web page.
driver.findElement(By locator).isDisplayed();
Ans. Using the isEnabled method, we can check if an element is enabled or not.
driver.findElement(By locator).isEnabled();
Ans. The difference between driver.findElement()
and driver.findElements()
commands is-
WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
List <WebElement> elements = driver.findElements(By.id(“value”));
Ans. Selenium is used for automating web-based applications only(or browsers only). If we want to handle window GUI elements then we can use tools like AutoIT.
AutoIT is freeware used for automating window GUI. The AutoIt scripts follow simple BASIC language like syntax. Also, it can be easily integrated with Selenium tests.
Ans. Robot API is used for handling Keyboard or mouse events.
Robot robot = new Robot();
//Simulate enter key action
robot.keyPress(KeyEvent.VK_ENTER);
Ans. File upload action can be performed in multiple ways-
<input type=”file” name=”fileUpload”>
Ans. Using profiles, we can handle accept the SSL untrusted connection certificate. Profiles are basically a set of user preferences stored in a file.
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver = new FirefoxDriver(profile);
Ans. Using Action class, drag and drop can be performed in Selenium. Sample code-
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(SourceElement)
.moveToElement(TargetElement)
.release(TargetElement)
.build();
dragAndDrop.perform();
Ans. JavaScript code can be executed in Selenium using JavaScriptExecuter. Sample code for javascript execution-
WebDriver driver = new FireFoxDriver();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("{JavaScriptCode}");
}
Ans. In order to accept or dismiss an alert box, the alert class is used. This requires first switching to the alert box and then using accept()
or dismiss()
command as the case may be.
Alert alert = driver.switchTo().alert();
//To accept the alert
alert.accept();
Alert alert = driver.switchTo().alert();
//To cancel the alert box
alert.dismiss();
Ans. HtmlUnitDriver is the fastest WebDriver. Unlike other drivers (FireFoxDriver, ChromeDriver, etc), the HtmlUnitDriver is non-GUI. On executing test scripts, no browser gets launched.
Ans. Using javaScript executor we can handle hidden elements-
(JavascriptExecutor(driver))
.executeScript("document.getElementsByClassName(locator).click();");
Ans. Page Object Model(POM) is a design pattern in Selenium. A design pattern is a solution or a set of standards that are used for solving commonly occurring software problems.
Now coming to POM – POM helps to create a framework for maintaining selenium scripts. In POM for each page of the application, a class is created having the web elements belonging to the page and methods of handling the events on that page. The test scripts are maintained in separate files and the methods of the page object files are called from the test scripts file.
In this way, we can create a robust automation framework using POM.
Ans. The advantages are POM are-
Ans. Page factory is an implementation of the Page Object Model in Selenium. It provides @FindBy annotation to find web elements. In addition, there is a PageFactory.initElements() method to initialize all web elements defined with @FindBy annotation.
public class SamplePage {
WebDriver driver;
@FindBy(id="search") WebElement searchTextBox;
@FindBy(name="searchBtn") WebElement searchButton;
//Constructor
public samplePage(WebDriver driver){
this.driver = driver;
//initElements method to initialize all elements
PageFactory.initElements(driver, this);
}
//Sample method
public void search(String searchTerm){
searchTextBox.sendKeys(searchTerm);
searchButton.click();
}
}
Ans. An object repository is the centralized location of all the objects or WebElements of the test scripts. In Selenium, we can implement an object repository using the Page Object Model as well as Page Factory design patterns.
Ans. A data-driven framework is one in which the test data is put in external files like CSV, Excel, etc. Basically, the test data is separated from the test logic that is written in test script files. The test data drives the test cases, i.e. the test methods run for each set of test data values.
TestNG provides inherent support for data-driven testing using @dataProvider annotation.
Ans. A keyword-driven framework is one in which the normal set of actions are associated with keywords and are kept in external files usually in tabular form.
For example, an action of launching a browser will be associated with the keyword – launchBrowser(), action to write in a textbox with keyword – writeInTextBox(webElement, textToWrite), etc.
The code to perform the action based on a keyword specified in the external file is implemented in the framework itself.
In this way, the test steps can be written in a file by a person of a non-programming background also (provided all the used keywords are implemented in the framework).
Ans. A hybrid framework is a combination of two or more frameworks. For example, a combination of data-driven and keyword-driven frameworks can be considered a hybrid framework.
Ans. Selenium Grid is a tool that helps in distributed testing. Using Grid, we can run test scripts in different machines having different browsers, browser versions, platforms, etc in parallel. In the Selenium grid, there is a hub that is a central server managing all the distributed machines known as nodes.
Ans. The advantages of the Selenium grid are-
Ans. A hub is a server or a central point in the Selenium grid that controls the test executions on the different machines.
Ans. Nodes are the machines that are attached to the selenium grid hub and have selenium instances running the test scripts. Unlike a hub, there can be multiple nodes in the selenium grid.
Ans. In the line of code Webdriver driver = new FirefoxDriver();
‘WebDriver’ is an interface and we are creating an object of the type WebDriver instantiating an object of FirefoxDriver class.
Ans. By creating a reference variable of the type WebDriver, we can use the same variable to work with multiple browsers like ChromeDriver, IEDriver, etc.
Ans. Apache POI API and JXL(Java Excel API) can be used for reading, writing, and updating excel files.
Ans. Log4j is an open-source API widely used for logging in Java. It supports multiple levels of logging like – ALL, DEBUG, INFO, WARN, ERROR, TRACE, and FATAL.
Ans. Logging helps in debugging the tests when required and also provides storage of the test’s runtime behavior.
Ans. TestNG(NG for Next Generation) is a testing framework that can be integrated with Selenium or any other automation tool. Moreover, it provides multiple capabilities like assertions, reporting, parallel test execution, etc.
Ans. Following are the advantages of TestNG-
Ans. The commonly used TestNG annotations are-
Ans. Some of the common assertions provided by testNG are-
Ans. A testng.xml file is used for configuring the whole test suite. In this file, we can create a test suite, create test groups, mark tests for parallel execution, add listeners, and pass parameters to test scripts. Later, this testng.xml file can be used for triggering the test suite.
Ans. Using @Parameter annotation and ‘parameter’ tag in testng.xml we can pass parameters to the test script.
Sample testng.xml –
<suite name="sampleTestSuite">
<test name="sampleTest">
<parameter name="sampleParamName" value="sampleValue"/>
<classes>
<class name="TestFile" />
</classes>
</test>
</suite>
//Sample test script:
public class TestFile {
@Test
@Parameters("sampleParamName")
public void parameterTest(String paramValue) {
System.out.println("Value of sampleParamName is - " + sampleParamName);
}
}
Ans. Using @DataProvider we can create a data-driven framework. Basically, we can pass test data to the associated test method and then multiple iterations of the test run for the different test data values passed from the @DataProvider method. The method annotated with @DataProvider annotation return a 2D array of object.
//Data provider returning 2D array of 3*2 matrix
@DataProvider(name = "dataProvider1")
public Object[][] dataProviderMethod1() {
return new Object[][] {{"kuldeep","rana"}, {"k1","r1"},{"k2","r2"}};
}
//This method is bound to the above data provider returning 2D array of 3*2 matrix
//The test case will run 3 times with different set of values
@Test(dataProvider = "dataProvider1")
public void sampleTest(String s1, String s2) {
System.out.println(s1 + " " + s2);
}
Ans. Listeners are used for performing some action in case an event gets triggered. Usually, testNG listeners are used for configuring reports and logging. One of the most widely used listeners in testNG is ITestListener interface.
It has methods like onTestSuccess, onTestFailure, onTestSkipped, etc. We need to implement this interface by creating a listener class of our own. After that using the @Listener annotation, we can specify that for a particular test class, a customized listener class should be used.
@Listeners(PackageName.CustomizedListenerClassName.class)
public class TestClass {
WebDriver driver= new FirefoxDriver();
@Test
public void testMethod(){
//test logic
}
}
Ans. Using the dependsOnMethods parameter inside the @Test annotation in TestNG, we can make one test method run only after the successful execution of the dependent test method.
@Test(dependsOnMethods = { "preTests" })
Ans. Using the priority parameter in @Test annotation in TestNG we can define the priority of test cases. The default priority of the test when not specified is integer value 0. Example-
@Test(priority=1)
Ans. The default priority of a test when not specified is integer value 0. So, if we have one test case with priority 1 and one without any priority then the test without any priority value will get executed first.
Ans. A Test method can be disabled from getting executed by setting the “enabled” attribute as false.
//In case of a test method
@Test(enabled = false)
public void testMethod1() {
//Test logic
}
//In case of test method belonging to a group
@Test(groups = {"NegativeTests"}, enabled = false)
public void testMethod2() {
//Test logic
}
Ans. In order to run the tests in parallel just add these two key-value pairs in the suite-
<suite name="ArtOfTestingSuite" parallel="methods" thread-count="5">
Ans. @Factory annotation helps in the dynamic execution of test cases. Using @Factory annotation, we can pass parameters to the whole test class at run time. The parameters passed can then be used by one or more test methods of that class.
For example – there are two classes TestClass and the TestFactory class. Because of the @Factory annotation, the test methods in class TestClass will run twice with the data “k1” and “k2”.
public class TestClass{
private String str;
//Constructor
public TestClass(String str) {
this.str = str;
}
@Test
public void TestMethod() {
System.out.println(str);
}
}
public class TestFactory{
//The test methods in class TestClass will run twice with data "k1" and "k2"
@Factory
public Object[] factoryMethod() {
return new Object[] { new TestClass("K1"), new TestClass("k2") };
}
}
Ans. @Factory method creates instances of test class and runs all the test methods in that class with a different set of data.
Whereas, @DataProvider is bound to individual test methods and runs the specific methods multiple times.
Trên đây là danh sách chọn lọc về 100 câu hỏi phỏng vấn Selenium. Thời gian tới Anh Tester đang soạn các câu hỏi và trả lời về các phần khác như TestNG, NUnit, SQL, Cucumber,...
Nếu bạn có thắc mắc về bất kỳ câu hỏi nào được liệt kê ở trên hoặc bạn muốn giúp Anh Tester thêm một số câu hỏi phỏng vấn khác về Selenium hay các phần khác, vui lòng cho mình biết trong phần comment bên dưới hoặc vào group chuyên Automation Testing để trao đổi thêm với mình và các bạn khác.
AN CẢM ƠN RẤT NHIỀU !!
Anh Tester
Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu