InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
How can we take a screenshot in Selenium? |
|
Answer» While executing the test cases, the test case may fail. The way while executing the test case manually we take a SCREENSHOT and place it in RESULT repository, same way things can be done by using Selenium WebDriver. We may need to capture SCREENSHOTS using Selenium WebDriver in scenarios -
Selenium is having an INTERFACE named TakesScreenshot to take the screenshot. This Instance has one method getScreenShotAs() will be used to take a screenshot during test execution and saves that screenshot at the desired location that we provide in the code. Syntax to capture and save the screenshot is - File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);For ex. File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(screenshot1.png); Syntax to store it in our local drive is - FileUtils.copyFile(screenshotFile, new File("filename_with_path")); For ex. FileUtils.copyFile(screenshotFile, new File("c:\\screenshot1.png")); package Managescreenshot; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class CaptureScreenshot { @Test public static void captureScreenMethod() throws Exception{ System.setProperty("webdriver.gecko.driver","c://Selenium Environment//Drivers//geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.manage().window().MAXIMIZE(); driver.get("https://www.facebook.com/capture-screenshot-using-selenium-webdriver"); File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshotFile, new File("C:\\screenshot1.png")); driver.close(); driver.quit(); } }When the script fails, to know where was the error in script capture a screenshot of the web page when the test case fails. By seeing screenshot, We can easily identify where exactly the script is failed. To take a screenshot of the failed test, we will place the entire code in try-catch block by placing the test steps in a try block and then screen capture statement in the catch block. In try block, if a test step fails then it goes to the catch block and captures a screenshot of the web page. package software testing material; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class CaptureFailScreenshot { public static void captureFailScreenMethod() throws Exception{ System.setProperty("webdriver.gecko.driver","C://Selenium Environment//Drivers//geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); try{ driver.get("https://www.facebook.com"); driver.navigate().refresh(); driver.findElement(By.id("emaile")).sendKeys("testmail@gmail.com"); //Statement with incorrect id }catch(Exception e){ File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshotFile, new File("C:\\incorrectuser.png")); } driver.close(); driver.quit(); } } |
|
| 2. |
What is Object Repository? How can we create an Object Repository in Selenium? |
|
Answer» Object Repository is a centralized location where you can STORE the object information. Object repository acts as an interface between Test script and application in identifying the objects during the execution. The collection of web elements belonging to AUT that is Application Under Test ALONG with their locator VALUES is termed as Object Repository. During execution whenever an element is required in the script, locator value is populated from the object repository. Instead of hard coding locators in the script object repository can be used and locators can be stored in a central location. Objects are stored in an excel sheet or XML file which populates inside the script whenever required. It is always recommended using an external file for object repository rather than hard coding the objects and its properties directly into our code and Reason is as it reduces the maintenance effort and provides a positive Return on investment. If any of the object properties change within the application under test, we can easily change it in external object repository file, instead of searching and doing updates for that object individually in the code. Before creating an object repository pre-requisite is project is CREATED and Selenium jars are added. 1. Create a new file with extension .properties For example, object_repo.properties To create new file right click on project> New > File 2. Select the parent folder and specify file name & extension. 3. Now Double click on file> File will open in Edit mode As object repository works on KEY and Value pair, you will specify Keys based on project and values we will give locator value. Let us take XPath for username, password and login button for facebook login page.
|
|
| 3. |
Can you debug the tests in Selenium IDE? If yes, then how? |
|
Answer» Selenium is an automation tool allow us to record and PLAYBACK application under test without having knowledge of scripting by using selenium IDE. Selenium IDE uses Selenese language to write test cases in different programming languages like Java, C#, PHP, Perl, Python, Ruby, etc. Resulting tests can be run on against different browsers. Debugging is the process of identifying and fixing the errors that may be present in the class. It is important to debug the code in order to remove the errors so that the application will run as expected. The following are the ways to debug the script.
To make the debugging process more robust, we can install and use Power Debugger add-on.
|
|
| 4. |
How is TestNG better than JUnit? |
|
Answer» TestNG is a testing framework that is developed as inspiration from the most popular JUnit framework used for java programming language. TestNG framework is introduced to OVERCOME the limitations of the JUnit framework. Most of the organizations are using the TestNG framework because of its advantages and additional supporting FEATURES. Features of TestNG framework: TestNG supports more productive and advanced features and it is easy to use. Let’s check which new features are available in the TestNG framework.
Advantage of TestNG v/s JUnit
|
|
| 5. |
What are the different types of navigation commands? |
|
Answer» Navigation commands enable selenium to open a new web PAGE URL, navigate to other page links available on the web page by clicking on that LINK or can navigate to Back or FORWARD or can refresh the webpage content again. Following are some types of navigation commands: 1) navigate().to(): This command is same like get() command, it opens a new BROWSER and will find the URL specified by the user. e.g. driver.navigate().to(“https://google.co.in/”); 2) navigate().forward(): This command is used to navigates to next page travelled by the user and is available in the browser history. e.g. driver.navigate().forward(); 3) navigate().back(): This command is used to navigates to back page user travelled from and is available in the browser history. e.g. driver.navigate().back(); 4) navigate().refresh():This command is used to refresh the CURRENT web page. All the web page content get reloaded again e.g. driver.navigate().refresh(); |
|
| 6. |
What is same-origin policy and how it can be handled? |
|
Answer» In the computing world, the same-origin policy is at the most important concept in the security model available for web applications. This policy permits SCRIPTS running on the pages that are originating from the same source or site. Origin is a combination of schemes, hostname and port number, to access each other’s DOM with no specific restrictions but at the same time, it prevents access to DOM on different sites. The Same-origin policy also applies to an XML, HTTP request and to web socket. This mechanism bears a particular significance for modern web applications that are using user logins are extensively dependent on HTTP cookies to maintain user sessions that are authenticated, as servers act based on HTTP cookie information to reveal sensitive information or take state-changing ACTIONS. A strict separation between content provided by the unrelated sites must be MAINTAINED on the client-side to prevent the loss of data confidentiality or integrity. Policies could have different specifications; all browsers are having an implementation of same-origin policy as it is an unavoidable security concern. An algorithm is used to evaluate the origin of the specified URL. For absolute URL, origin contains protocol, host and port number. If the URL is not absolute, then a unique identifier is used. Any two resources are considered as from the same origin only if all of the values are exactly the same. Same Origin policy prevents JAVASCRIPT code from accessing elements from a domain that is different from where it was launched. To overcome the Same-origin policy, Selenium RC was introduced. Prior to Selenium RC, testers REQUIRE to install local copies of both Selenium Core and the web server containing the web application being tested so they would belong to the same domain. |
|
| 7. |
How to upload a file? |
|
Answer» There are two ways you can upload file in selenium WebDriver, one is using SendKey method when there is text box AVAILABLE to enter the file’s name and second is using AutoIT Script tool when there is no text box to enter the file’s name.
Syntax is – //locate browse button WebElement browse =driver.findElement(By.id("id value")); //pass the path of the file to be uploaded using Sendkeys method browse.sendKeys("D:\\SoftwareTestingMaterial\\UploadFile.txt"); //click on submit button driver.findelement(By.id(“id value”)).click;
WinWaitActive("File Upload"); Name of the file upload WINDOW (Windows Popup ame: File Upload) Send("logo.jpg"); File name Send("{ENTER}");
|
|
| 8. |
How to perform drag and drop using WebDriver? |
|
Answer» Now a day, many web APPLICATIONS have the functionality to drag an element and drop it on a defined area. There are two METHODS in Actions class which SUPPORTS drag and drop -
Here we pass two parameters, first "sourcelocator" is the element we need to drag. The second PARAMETER is "Destinationlocator" which is the element on which we need to drop the first element.
Here we pass three parameters, first "source locator", the second is x-axis pixel VALUE of the 2nd element on which we need to drop the first element and third is y-axis pixel value of the 2nd element. Ex. Actions act=new Actions(driver); act.dragAndDrop(From, To).build().perform(); |
|
| 9. |
How to perform right-click using WebDriver? |
|
Answer» In some scenarios, you might NEED to do the right click action/context on an element to perform some actions. Use Selenium WebDriver class Actions to work on Mouse and Keyboard Actions. Selenium has a built-in capability to handle various types of keyboard and mouse events. In order to perform action events, we need to use org.openqa.selenium.interactions Actions class, user-facing API for performing complex user gestures. Instead of USING Keyboard or Mouse directly, you can use the selenium actions class. Let us see the scenario to automate
|
|
| 10. |
What is an alternate way to click on the Login button? |
|
Answer» In selenium, we can click on the Login button in different ways - 1. Navigate to login button. Once control is on the login button perform click() ACTION. package clicklogin; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; public class LoginClick { public static void main(String[] args) throws InterruptedException{ WebDriver driver = new FirefoxDriver(); //LAUNCHING site driver.get("http://facebook.com"); // click on the LogIn button driver.findelement(By.id("u_0_a")).click(); //Thread.sleep just to notice event Thread.sleep(3000); //Closing the driver instance driver.quit(); } }2. ANOTHER way to perform click on Login button using action class package clicklogin; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; public class LoginClick { public static void main(String[] args) throws InterruptedException{ WebDriver driver = new FirefoxDriver(); //Launching site driver.get("http://facebook.com"); // click on the LogIn button WebElement loginBtn = driver.findElement(By.id("u_0_a")); Actions act = new Actions(driver); act.moveToElement(loginBtn).click().perform().build(); //Thread.sleep just to notice event Thread.sleep(3000); //Closing the driver instance driver.quit(); } }package clicklogin; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; public class LoginClick { public static void main(String[] args) throws InterruptedException{ WebDriver driver = new FirefoxDriver(); //Launching site driver.get("http://facebook.com"); // click on the Log In button WebElement loginBtn = driver.findElement(By.id("u_0_a")); Actions act = new Actions(driver); act.SendKeys(Keys.Enter); //Thread.sleep just to notice event Thread.sleep(3000); //Closing the driver instance driver.quit(); } } |
|
| 11. |
What are Desired capabilities? |
|
Answer» The desired capability stores the browser properties like browser NAME, browser version, the path of the browser driver in the system, etc in a series of key/value pairs, to determine the behaviour of the browser at RUN time. You can also use the Desired capability to configure the driver instance of Selenium WebDriver like FirefoxDriver, ChromeDriver, InternetExplorerDriver. Every Testing scenario is executed on a specific testing environment and this testing environment can be a web browser, Mobile device, mobile emulator, mobile simulator, etc. The Desired Capabilities Class TELLS WebDriver, which environment you going to use in the test script. The setCapability method of the DesiredCapabilities Class can be used in Selenium Grid to perform a parallel execution on different machine configurations. Desired capability is used to set the browser properties, Platform Name that is used when executing the test cases. In the case of mobile automation, we perform the tests on different mobile devices, the Mobile Platform ex. iOS, Android Platform Version Ex. 3.x,4.x in Android can be set. Desired Capabilities are more USEFUL in mobile application automation, where the browser properties and the device properties can be set. And in Selenium grid to run the test cases on a different browser along with different operating systems and versions. Example- // Create a new OBJECT of DesiredCapabilities class. DesiredCapabilities capabilities = new DesiredCapabilities(); // set the android deviceName desiredcapability. capabilities.setCapability("deviceName", "your Device Name"); // Set the BROWSER_NAME desiredcapability. capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome"); // Set the android VERSION desiredcapability. capabilities.setCapability(CapabilityType.VERSION, "5.1"); // Set the android platformName desired capability. capabilities.setCapability("platformName", "Android"); |
|
| 12. |
What is ElementNotVisibleException? |
|
Answer» You often get ElementNotVisibleException when you execute selenium scripts when WebDriver locate WEB element on the current webpage but the element is not visible on the screen. There are many reasons that accumulate for this exception. Below are the reasons for ElementNotVisibleException – Not locating correctly
Solution: Locate correct and specific element. The desired element is overlapped by another web element
Solution:
Ajax calls
Solution:
Webdriver is unable to auto-scroll to the desired element
Solution:
|
|
| 13. |
What is Fluent Wait and how to use it in WebDriver? |
|
Answer» WebDriver has various wait commands that help to overcome issues due to variation in a time lag. Web driver checks whether an element is present or visible or enabled or clickable etc. The Fluent wait is one of the Explicit waits. In Fluent wait, you can DEFINE the maximum AMOUNT of time for a condition and frequency with which to CHECK the condition before throwing an exception. In short, fluent wait tries to FIND the web element repeatedly at regular intervals of time until the timeout or till the object GETS found. Mainly FluentWait command is used when web elements are visible in few seconds and sometimes take more time than usual. Two main components of fluent wait are - Timeout value and polling frequency FluentWait syntax is - Wait<WebDriver> wait = new FluentWait(WebDriver reference) .withTimeout(timeout, SECONDS) .pollingEvery(timeout, SECONDS) .ignoring(Exception.class); Wait<WebDriver> wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(5, SECONDS).ignoring(NoSuchElementException.class); |
|
| 14. |
What is an explicit wait? |
|
Answer» WEBDRIVER has various wait commands that help to overcome issues due to variation in a time lag. WebDriver checks WHETHER an element is present or VISIBLE or ENABLED or clickable etc. The explicit wait tells the WebDriver to wait for certain conditions (Expected Conditions) or wait till the maximum time exceeded before throwing an exception. The explicit wait is an INTELLIGENT wait but can be applied only on specified elements. As explicit wait waits for dynamically loaded Ajax elements, it is a better option than implicit wait. We need to provide “ExpectedConditions” along with Explicit wait. Syntax: WebDriverWait wait = new WebDriverWait(WebDriverReference,TimeOut);Below is the list of Expected Conditions used in Explicit Wait
|
|
| 15. |
What is Implicit wait? |
|
Answer» Before throwing and exception IMPLICIT wait tells WebDriver to wait for a CERTAIN amount of time. WebDriver will wait for the element based on the time we set before it throws an exception. We need to set some wait time to make WebDriver to wait and default setting is 0 (zero). Implicit Wait is in place till the browser is open. Based on time fixed for the implicit wait, the same wait time will be applied to all elements for search. Syntax: driver.manage().timeouts().implicitlyWait(TimeOut,TimeUnit.SECONDS);Two PARAMETERS required for Implicit wait are time as an integer value and second is time measurement in terms of seconds, minutes, milliseconds, microseconds, days, hours, ETC. |
|
| 16. |
How do you clear the contents of a text box? |
|
Answer» Selenium WebDriver has predefined method CLEAR() which is used to clear the text entered or displayed in the text fields. Some times default text is displayed in the text box or sometimes due to cookies stored pre-populated text is displayed in a text box and we need to clear that text before entering NEW text otherwise we might get the WRONG result. To AVOID test failure it is always a best practice to clear text before entering new text. driver.findElement(By.id(“id Value”)).clear(); public void clearTheTextBoxField () { _driver.findElement ( By.cssSelector ( “#textbox1” )).clear (); }Let us see the code for clear text. We will use google.com for our reference. In this, we are sending some text first and then clear it. package testPackage; import java.awt.AWTException; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import multiScreenShot.MultiScreenShot; public class textClear { public static void main(STRING[] args) throws IOException, AWTException { WebDriver driver =new FirefoxDriver(); driver.get("https://google.com"); //maximize the window driver.manage().window().maximize(); WebElement searchBox = driver.findElement(By.name("q"); //Send text to the web element searchBox.sendKeys("Selenium clear text testing"); //clear text searchBox.Clear(); } } |
|
| 17. |
How to get a typed text from a text box? |
|
Answer» Additional information about an HTML is stored in Attributes and comes in pair name =”value”. In <div class=”my-class”></div> example div is tag and class is attribute with value ‘my-class’. The property PRESENTS an attribute in the HTML DOM tree. In the above example, the attribute would have a property named className and value my-class. HTML defines attributes and DOM defines properties. Attributes may have 1:1 mapping with property or may not have. The ID is an example of 1:1 mapping. Attributes are stored in HTML text document and properties are in the HTML DOM tree. Attributes carry initial default value and the attribute does not change whereas HTML properties can change. To verify test cases, during automation we need to retrieve values of attributes or properties of web elements. In case of a bus ticket booking application, Colour of the available seat colour is green and BOOKED seat colour is red. To book the ticket first we need to check whether a seat is available or not. And to test this, we need to fetch colour attribute value using the script and based on output value we need to perform further operations. To fetch attribute value, selenium WebDriver has predefined getAttribute(value) method which returns the value of the attribute of the web element as a string. If the attribute exists, getAttribute method returns value of the property with the given name, and if it does not exist then returns value of the attribute with the given name. Please NOTE, when the given name is “class”, then “className” property is returned and when given name is “readOnly”, the “readOnly” property is returned. To use getAttribute() method on a specific element, first, locate the web element and then call getAttribute() method on it by specifying the attribute. Below is the code explaining getAttribute() method – WebElement we = driver.findElement(By.class("class Value")); String value = we.getAttribute("id");IMPORT org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class GetAttributes { public WebDriver driver; private By bySrchButton = By.name("btnK"); @BeforeClass public VOID setUp() { driver = new FirefoxDriver(); driver.get("http://www.google.com"); } @Test public void getAttribute_ButtonName() { WebElement googleSrchBtn = driver.findElement(bySrchButton); System.out.println("Name of the button is:- " +googleSrchBtn.getAttribute("name")); } @Test public void getAttribute_Id() { WebElement googleSrchBtn = driver.findElement(bySrchButton); System.out.println("Id of the button is:- "+ googleSrchBtn.getAttribute("id")); } @Test public void getAttribute_class() { WebElement googleSrchBtn = driver.findElement(bySrchButton); System.out.println("Class of the button is:- "+ googleSrchBtn.getAttribute("class")); } @Test public void getAttribute_InvalidAttribute() { WebElement googleSrchBtn = driver.findElement(bySrchButton); //Negative test as 'Status' attribute does not exist,will return null value System.out.println("Invalid Attribute status of the button is:- "+ googleSrchBtn.getAttribute("status")); } @Test public void getAttribute_ButtonLabel() { WebElement googleSrchBtn = driver.findElement(bySrchButton); System.out.println("Label of the button is:- "+ googleSrchBtn.getAttribute("aria-label")); } @AfterClass public void tearDown() { driver.quit(); } } |
|
| 18. |
What is Action Class? |
|
Answer» Selenium has a built-in capability to handle various types of keyboard and mouse events. In order to perform action events, we need to use org.openqa.selenium.interactions Actions class, user-facing API for performing complex user gestures. Instead of using Keyboard or Mouse directly, you can use the selenium actions class. Syntax to create an object ‘action’ of selenium action class –
Here element is the web element we have CAPTURED and perform() method is used here to execute the action. To click on Element -
Keyboard Events Using Selenium Actions Class API:
Mouse Events Using Selenium Actions Class API:
|
|
| 19. |
How to take multiple screenshots in Selenium WebDriver? |
|
Answer» In testing, it is very much necessary to store test result DATA to prove the certain test is passed/failed or functionality is covered or not and you can take SCREENSHOTS as test result or proof, which can be used for reference later. The same way we need to take screenshots as proof in automation testing also. During automated testing of continuous application flow, you might want to capture a series of screenshots. Selenium WebDriver has a nice little utility MultiScreenShot to capture multiple screenshots. This utility ALLOWS you to take a screenshot of individual elements and minimize the browser. We will see how to setup MultiScreenShot utility with selenium WebDriver and capture multiple screenshots. We will use Google.com for the explanation.
Full page screenshot is taken when you call the method and this method accepts WebDriver object as an argument. Example: multiScrShot.multiScreenShot(driver); Screenshot of elements on a page is taken when you call method and method accepts WebDriver object as argument and WebElement object Example: mShot.elementScreenShot(driver, driver.findElement(By.id("search-submit"))); Minimize the browser window when the browser window is maximized. No argument is required to pass. Example: multiScrShot.minimize(); package testPackage; import java.awt.AWTException; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import multiScreenShot.MultiScreenShot; public class TestMultiScrShot { public static void main(String[] args) throws IOException, AWTException { MultiScreenShot multiScrShot=new MultiScreenShot("C:New","TestMultiScrShot"); WebDriver driver =new FirefoxDriver(); driver.get("https://google.com"); //maximize the window driver.manage().window().maximize(); //take full screenshot using MultiScreenShot class multiScrShot.multiScreenShot(driver); //take element screenshot using MultiScreenShot class multiScrShot.elementScreenShot(driver, driver.findElement(By.name("btnK"))); //NAVIGATE to https://nikasio.com driver.navigate().to("https://nikasio.com"); //take element screenshot using MultiScreenShot class multiScrShot.elementScreenShot(driver, driver.findElement(By.id("slide-2-layer-2"))); //take full screenshot using MultiScreenShot class multiScrShot.multiScreenShot(driver); //minimize the window using MultiScreenShot class multiScrShot.minimize(); driver.quit(); } } |
|
| 20. |
What Types Of Data Have You Handled In Selenium For Automating Web Applications? |
|
Answer» Data is very important and critical information to run automation successfully. Data can be in different forms to serve different purposes. For example in automation, input data includes test cases, and it could be test data that feeds into test cases as parameters. Selenium supports Excel, CSV, XML, JSON, SQL, YAML data types for automation. 1. Excel Data. Excel is a popular data format used widely in automation. It can store test cases as well as test data. Excel format is not only flexible but also support Create/Delete/Update/Delete (CRUD) operations also. All language that Selenium supports have ready-made LIBRARIES to access and manipulate excel data. 2. XML Data. An XML document is in a format readable by both humans and machines. XML is a web standard and faster than Excel in reading or WRITING data. There are built-in or third-party XML parsers available to manage the data. XML has a unique feature to search specific elements called XPath. Xpath is a known term in Selenium which traverses the DOM of a web page. Many times Excel and XML are used together in Selenium automation projects. You can write the test cases in Excel and create a macro to convert them in XML format. The automation suite reads the test cases from XML and executes them. 3. SQL Data. SQL data is customizable and enables fast data access. It stores both the test cases and configuration or settings as required. Separate database software like MySQL/MongoDB/SQL/Oracle is required to make it work and install any of this software to prepare a new setup which is an additional overhead for the automation engineers. 4. CSV Data. CSV that is comma-separated-values, is the simplistic way of organizing test data in tabular format. CSV data is a text file with extension .csv and it represents a sequence of rows and columns delimited by commas. Every row of CSV file is a record while every column mapped to a field. As most programming LANGUAGES come with standard libraries to read/write text files it is trivial to access CSV. Excel supports this TYPE of data and can handle it the same way. 5. JSON Data. JSON (JavaScript Object Notation) supports a light-weight data interchange format. JSON data is compact and fast and we can use it to represent the test data replacing Excel and XML formats. For large data SIZE, JSON would deliver better performance. 6. YAML Data. YAML(YAML Ain’t Markup Language) is a human-readable language for data serialization. For holding configuration this type of data format is ideal. YAML is a superset of JSON language and stores both JSON and XML data within itself. |
|
| 21. |
How would you find broken links on a webpage with the Webdriver? |
|
Answer» Links or URLS which are not reachable or FUNCTIONING are broken links due to some error. There are different status codes for HTTP which are having different purposes. 2XX is valid request status and the URL will always have status 2XX. Status 4XX and 5XX are for invalid HTTP request out of which 4XX status code is for client-side error and 5XX status code are for server response error. It is not possible to confirm that the link is working or not till we click on the link and confirm it. It is always GOOD practice to make sure that there are no broken links because the end-user should not land into an error page. You can not check all links manually, because each web page may have a large number of links & manual process has to be repeated for all pages. It will be a tedious task. With Selenium, we can automate the process. |
|
| 22. |
How Can You Access A Database From Selenium? |
|
Answer» Selenium is limited to browser testing. To access databases using Selenium WebDriver we need to use JDBC that is Java Database Connectivity. JDBC is a SQL level API to execute SQL commands and is responsible for the connection between Java and different databases. So use JDBC Driver to connect to the Database with Selenium when using Java as a programming language. To connect to the database first download the JDBC jar FILE and add it to your project. Also you need database URL with port, user ID and password. Syntax in order to make connection to the database is - DriverManager.getConnection(URL, "userid", "password" )Where, URL format is jdbc:<dbtype>://<host>:3036/db_name" and <dbtype>- database driver. To connect to oracle database <dbtype> will be "oracle" So for Oracle database with NAME ‘demo’ URL will be jdbc:oracle://<host>:3036/demo So code for database connection will be Connection con = DriverManager.getConnection(dbUrl, username, password);You need to load JDBC driver and code is Class.forName(“com.oracle.jdbc.Driver”);Once connection is established you need to execute queries and for that you need to declare STATEMENT object to send queries Statement stmt = con.createStatement();Now use the executeQuery method to execute the SQL queries stmt.executeQuery(“Select * from demo”);Store the result of executed query in the ResultSet Object ResultSet rs= stmt.executeQuery(stmt); Import java.sql.Connection; Import java.sql.DriverManager; Import java.sql.ResultSet; Import java.sql.SQLException; Import java.sql.Statement; Import org.testng.annotations.Test; public class TestDatabase { public void TestVerifyDB () { Class.forName ( “Sun.jdbc.odbc.jdbcodbcDriver” ); STRING dblocation = “ C: \\ Users\\Desktop\\DB\\TestDB1.accdb”; Connection con = DriverManager.getConnection ( dbUrl, username, password ); Statement smt = con.createStatement (); ResultSet rs = smt.executeQuery ( “Select*from TestDB1” ); |
|
| 23. |
What is TestNG, what are the benefits of it? |
|
Answer» TestNG is an open-source testing framework inspired by JUnit and NUnit but presenting some new functionality that makes it simply easy, effortless, and powerful to use where NG of TestNG stands for Next Generation. It is same as JUnit but it is more robust than JUnit. To make execution more efficient and powerful more functionality is added. It is very much DATA-Driven but is powerful than JUnit. Most of the negative TRAITS of the older framework are removed from TestNG and it gives developers the ability to write more FLEXIBLE and powerful tests with the help of annotations, grouping, sequencing and parameterizing. Advantages of TestNG are -
|
|
| 24. |
Explain methods to implement the Robot class in Selenium? |
|
Answer» Below are the few methods that help in the easy execution of test scripts required for Robot class implementation.
Let us understand these methods in details - Example : robot.keyPress(keyEvent.VK_UP); will press UP key on the keyboard.
Example: robot.keyRelease(keyEvent.VK_CAPS_LOCK); will release the pressed caps lock key on the keyboard.
Example : robot.mouseMove(coordinates.get.X(),coordinates.get.Y());will move the mouse over X and Y coordinates.
Example - robot.mousePress(InputEvent.BUTTON1_MASK); will press the mouse button
Example - robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); will release the right click of the mouse. Let us see the code on how to declare robot class - Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_DOWN); //will press down key on the keyboard robot.keyPress(KeyEvent.VK_TAB); // will press tab key on the keyboar |
|
| 25. |
What is the robot class? |
|
Answer» In some automation scripts, there is a need to use mouse or keyboard actions to interact with OS like Alerts, download pop-up, Print pop-up, etc. and Selenium Webdriver cannot handle these OS pop-ups or applications. A Robot is a class in Selenium and is used to generate NATIVE system INPUT events for test automation, where you need control over the mouse and keyboard. To handle the OS POPUPS which WebDriver does not handle, the Robot class was introduced. The MAIN purpose of ow Robot class is to assist automation testing for Java platform implementations. In other words, the Robot class provides control over mouse and keyboard devices. This class is easy to implement and easily integrate with the automation framework. Let us see the importance of the Robot class -
|
|
| 26. |
What is Continuous Integration (CI), what are its benefits? |
|
Answer» Continuous Integration is a technique which regulates the development process by automating the BUILD and testing code on every commit made to the version control. Continuous Integration makes sure that NEW changes do not have any adverse effect on the build and existing functionality is not affected. In the case of a failed scenario, everyone including the one responsible for the changes will know about the FAILURE without delay. With this timely reporting, developers find fair time to fix the issues and get prompt feedback. Continuous Integration encourages best practices amongst developers by allowing them to merge their changes with other's code before checking into a shared repository. On time code integration eliminates changes of conflicts, duplication of functionality. CI suggests using a version control system that supports Git workflows for intelligent branching. CI proposes having the main BRANCH that keeps the stable code that can be used to deliver build at any time. At the same time developer can create transient features branches to start his work without interrupting others. Developers need to sync his code with Main Branch at regular intervals. On feature-complete, a developer should merge his code into the main branch after verification |
|
| 27. |
What are the different network protocols that Selenium supports? |
|
Answer» The TWO most commonly used network protocols are HTTP and HTTPS. There are multiple ways to handle both protocols in Selenium. HTTP protocol - No Authentication - When a website is using HTTP protocol and does not require any authentication, it is easy to handle WebDriver driver = new ChromeDriver(); driver.get("http://destination-url/"); Basic authentication - Many WEBSITES apply basic authentication scheme before allowing access to the home page. You can handle basic authentication in three ways- i) Using WebDriverWait and Alert classes to implement basic authentication for HTTP. WebDriverWait testwait = new WebDriverWait(driver, 10); Alert testalert = testwait.until(ExpectedConditions.alertIsPresent()); testalert.authenticateUsing(new UserAndPassword(**user**, **pass**));ii) pass user/pass pair within the HTTP URL as a parameter to WebDriver's Get method. String target = “http://user:pass@host”; public void LOGIN(String username, String password){ WebDriver driver = new ChromeDriver(); String URL = "http:// + username + ":" + password + "@" + "website link"; driver.get(URL); driver.manage().window().maximize(); }iii) Setting up browser preferences using the Selenium's profile classes. FirefoxProfile FF = new FirefoxProfile(); FF.setPreference("network.http.phishy-userpass-length", 255); driver = new FirefoxDriver(FF); driver.get("http://user:pass@www.targetsite.com/");HTTPS protocol - HTTPS is a secured protocol of HTTP and it encrypts communication exchanged between the web server and the browser. HTTPS protocol uses an SSL certificate that downloads onto the browser on initiating the first request. SSL certificate has a public key for encrypting the data transfer from client to server. In short, we need to handle the SSL certificates in Selenium. To manage SSL in different browsers you need to use different approaches. Handle SSL in Firefox - In firefox SSL is enabled using Selenium Profile APIs. First load the profile of RUNNING browser instance. ProfilesIni pf = new ProfilesIni(); FirefoxProfile ff = pf.getProfile ("myProfile");Set the following properties to avoid security exception while opening the HTTPS site ff.setAcceptUntrustedCertificates(true); ff.setAssumeUntrustedCertificateIssuer(false);Now create Firefox driver instance using profile object. WebDriver driver = new FirefoxDriver (ffProfile);Handle SSL in Chrome - Chrome need to set SSL options via desired capabilities of selenium WebDriver. First prepare DesiredCapabilities instance DesiredCapabilities set_ssl = DesiredCapabilities.chrome(); set_ssl.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true); WebDriver driver = new ChromeDriver (set_ssl);Handle SSL in IE - In IE SSL is managed with two different methods. i) Native JavaScript CODE - driver.navigate ().to ("javascript:document.getElementById('overridelink').click()"); |
|
| 28. |
What are various build and deploy tools apart from Maven used in the industry? |
|
Answer» Maven builds the code and manages dependencies on the fly. Also due to its ability for SUPPORTING deployments Maven is used wide-spread. Maven makes a lot of post-development tasks easy. There are a bunch of other tools you can use instead of Maven.
Gradel suggests a polyglot build system that integrates the project with different technologies and programming languages. Gradle makes version management easier than Maven with the help of dynamic versioning. |
|
| 29. |
What is parameterization in TestNG? How to pass parameters using testng.xml? |
|
Answer» We always wish to TEST our software using different sets of data to make sure software works properly under a different set of data. Parameterization is the technique USED to define values in the testng.xml file and send these values as parameters to the test case. Parameterization is useful when you want to PASS multiple data to different test environments. We need to pass multiple data to the application at runtime. Below is the CODE in which empName is annotated as a parameter public class ParameterizedTest1{ @Test @Parameters("empName") public void parameterTest(String myName) { System.out.println("Parameterized value is : " + myName); } }To pass the parameter value using testng.xml, USE the 'parameters' tag. Look at the below code - <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name=”CustomSuite"> <test name=”CustomTest”> <parameter name="empName" value=”Donald"/> <classes> <class name="ParameterizedTest1" /> </classes> </test> </suite> |
|
| 30. |
What is the significance of testng.xml? |
|
Answer» Selenium does not support report generation and test case management, we use the TESTNG framework with selenium to support these features. TestNG is more advanced than JUnit and implementation of annotations is easy. The test suite is not defined in TESTING source code and it is represented in an XML file because the suite is a COLLECTION of test cases and an execution is the feature of the test suite. To execute test cases in a suite or group of test cases, you need to create a testng.xml file. The testng.xml file contains the NAME of all classes and methods that needs to be executed as a PART of execution flow. Advantages of using testng.xml file are -
|
|
| 31. |
Why do you need Cross Browser Testing? |
|
Answer» Every website is comprised of n number of technologies that are USED in the backend and frontend. Three major technologies used for the front end and in the rendering are HTML5, CSS3, and JavaScript. Every browser has a different rendering engine to compute these three technologies. Chrome uses Blink, Firefox uses GECKO and IE uses edge HTML and Charka. Because of these rendering engines, the same website renders complete differently in all these different browsers and that is the reason why you need cross-browser testing. To ensure the website works fine and functions the same across different browser versions and on different operating systems, cross-browser testing is required. Reasons for why cross-browser testing is required are -
|
|
| 32. |
How to build a Selenium Grid? |
|
Answer» To execute scripts two important LIBRARY packages DesiredCapabilities object and RemoteWebDriver object are required. DesiredCapabilities library is used to set browser type and the OS of Node. Use the below code to import the DesiredCapabilities object. import org.openqa.selenium.remote.DesiredCapabilities;The RemoteWebDriver object is used to select the Node on which TEST will be executed. Use the below code to import RemoteWebDriver object. import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.remote.RemoteWebDriver;You can mouse HOVER on the logos of browser present in the Selenium Hub console to get the details like browserName and platform of the Node. Use below code to setup grid package TestGrid; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.net.MalformedURLException; import java.net.URL; import org.junit.Assert; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class TestGrid { static WebDriver driver; static String nodeUrl; @BeforeTest public void setup() throws MalformedURLException { nodeUrl = "http://192.168.2.11:4444/wd/hub"; DesiredCapabilities capabilities = DesiredCapabilities.CHROME(); capabilities.setBrowserName("chrome"); capabilities.setPlatform(Platform.WINDOWS); driver = new RemoteWebDriver(new URL(nodeUrl), capabilities); } @Test public void simpleTest() { driver.get("https://nikasio.com"); } @AfterTest public void afterTest() { driver.quit(); } }Here the test is divided into three test annotations @BeforeTest, @Test, and @AfterTest. In @BeforeTest, DesiredCapabilities and RemoteWebDriver objects are used to configure Node. In @Test directed Node to navigate to nikasio.com's home page.In @AfterTest, directed Node to quite the browser instance. On execution, you will get below output. May 18, 2018 4:15:07 PM org.openqa.selenium.remote.ProtocolHandshake createSession
|
|
| 33. |
How to configure the Node? |
|
Answer» Nodes are host machines on which the TESTS are RUN. These tests are launched by the Hub. Hub can launch ONE or more nodes on remote machines or on the same machine where Hub is located. Node executes tests you loaded on the hub. To configure nodes, you need to download the Jar files on the Node machines and place it on any directory of CONVENIENCE. Open windows command prompt and execute below command- java-DWebDriver.chrome.driver=C:chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.2.11:4444/grid/register To set a Node on the same machine as you Hub, you need to open another command prompt other than Hub prompt.
To check Nodes are registered, open and browser and navigate to http://localhost:4444/grid/console. Once Selenium Grid is CONFIGURED, you can proceed with the test script execution on Nodes. |
|
| 34. |
How to configure Hub on a Windows machine? |
|
Answer» Before proceeding further with configuration make sure Java is installed on your system and environment variable is set. Now to configure Hub, first, you need to download the SELENIUM Server JAR FILE 'selenium-server-standalone-3.141.59.jar' from Seleniumhq's website. Place this Jar file in an appropriate directory (says c:/Selenium Server. ) Open windows COMMAND prompt and navigate to the directory where Jar file is stored. for example c:>Selenium Server Now EXECUTE below command - java -jar selenium-server-standalone-3.141.59.jar -role hubWhere selenium-server-standalone-3.141.59.jar is the downloaded jar file. -role flag is used to set a host machine as Hub. One thing to keep in mind is Hub will be up and running as long as the command prompt is open. By default, the selenium grid uses 4444 port for web interfaces. To check whether the Hub is up and running open browser and navigate to http://localhost:4444 and you will see below UI. |
|
| 35. |
Explain Selenium Grid architecture. |
|
Answer» We know Selenium GRID is ONE of the important tools of Selenium suite and it functions on Node and multiple hub basis. LET us see what is Hub and Node? and how it works?
You need to configure Hub first and the register nodes with Hub to execute tests. |
|
| 36. |
What Is Selenium Grid? |
|
Answer» One of the important tools in the SELENIUM suite is Selenium Grid. Selenium grid has the capability of co-ordinating WebDriver tests or RC tests that can run on MULTIPLE browsers simultaneously. Selenium Grid can initiate WebDriver tests or RC tests on different operating systems. Selenium Grid even initiates or EXECUTES tests hosted on different machines. There can be only one hub and it will be a central part of the Selenium Grid setup and nodes are test machines on which tests are run. Let us see how it works? Grid hosts a Hub-Node architecture. Here there is one Hub acts as the master and one or more nodes that ACT as slaves. Consider you have 100 tests that are required to be executed simultaneously on different machines in different combinations of operating systems and browsers. Each MACHINE has a different OS and inside OS, the test is executed on different browsers. This will save a lot of your execution time. |
|
| 37. |
Why & When To Use Selenium Grid? |
|
Answer» Many web browsers are available and used nowadays. Users may use FIREFOX, or Safari, or Chrome, or Internet Explorer browser for reading. Users may use different versions of the browsers and also may be running browsers on any OS like Windows, or Mac, or Linux. To help users get the best user experience, you need to go extra miles and test Web application on different browsers along with different platforms. You need to test applications on different browsers and OS. You need to put extra effort and spend TIME testing your web application on every possible OS and available browser. Is it possible and feasible? Now how to make it possible? Here Selenium grid FITS well and saves your time and energy. Now the question is, Is it possible to set up selenium grid infrastructure using local systems? It is challenging to MAINTAIN Selenium Grid with all required browsers and operating systems and for that multiple online platforms PROVIDE an online Selenium Grid which you can access to run selenium scripts. |
|
| 38. |
How to run multiple test suite in selenium by using testing? |
|
Answer» We can configure our WebDriver test or WebDriver test suites for software testing project in testng.xml file. If we have two/multiple classes in test suite we can run those classes in the same test as well as two different tests too. Let's take a simple example here: Create 3 classes under project = TestNGOne and package = TestNGOnePack as below. BaseClassOne will be used for initializing and closing WebDriver instance, ClassOne and ClassTwo will be used as test classes.
The above class will be base class and be used to initialize and close the WebDriver instance.
Above ClassOne is inherited or created from BaseClassOne.
Above ClassTwo is also inherited or created from BaseClassOne. Configure testng.xml to run two classes in one test: Copy the below-given lines in the testng.xml file and run it as TestNg Suite. <suite name="Suite One" > <test name="Test One" > <classes> <class name="TestNGOnePack.ClassOne" /> <class name="TestNGOnePack.ClassTwo" /> </classes> </test> </suite>When execution is completed, View execution results report. Configure testng.xml to run two classes in two tests: Now if we want to run both classes as SEPARATE test then we have to configure testng.xml file as below <suite name="Suite One" > <test name="Test One" > <classes> <class name="TestNGOnePack.ClassOne" /> </classes> </test> <test name="Test Two" > <classes> <class name="TestNGOnePack.ClassTwo" /> </classes> </test> </suite>Here, "ClassOne" is included in 'Test One" test and "ClassTwo" is included in 'Test Two" test. Now run below given testng.xml file and verify results. After comparing both results. In the 1st example, Both classes are executed under the same test but in the second example, both classes are executed under separate tests. This way you can configure the testng.xml file as per your requirement. |
|
| 39. |
What are the types of WebDriver APIs available in Selenium? |
|
Answer» Selenium Webdriver is itself an API and it’s an interface. Selenium hierarchy contains two WebDriver - Remote WebDriver and Selenium WebDriver. Remote WebDriver is a class that implements the Selenium WebDriver interface whereas browser classes ChromeDriver(), FirefoxDriver() and etc. extend the Remote WebDriver. There are many APIs and methods in Selenium and following are some as follows: 1. Navigation Commands:
Driver.navigate().to("http://qatechhub.com");
Driver.get("http://qatechhub.com");
Driver.navigate().back();
Driver.navigate().forward();
Driver.navigate().refresh(); 2. Resizing Windows:
3. DELETING Cookies: Delete cookies in Selenium as per below command Driver.manage().deleteAllCookies();This will not actually delete the physical cookies file from the browser but it bypasses these files that cookies don’t appear in the browsing experience. 4. Closing the Browser:
5. Different Get Methods:
6. Searching WebElements: To search for web elements on a web page below methods are used:
7. Mouse Operations: Mouse operations like mouse HOVER, drag, and drop, right clickor double click with Selenium actions class is used: Mouse Hover: Actions action = new Actions(Driver); WebElement mobileElement = Driver.findElement(By.linkText("Mobile & Accessories")); action.moveToElement(mobileElement).build().perform();Drag and Drop: WebElement source = Driver.findElement(By.id("draggable")); WebElement target = Driver.findElement(By.id("droppable")); Actions action = new Actions(Driver); action.dragAndDrop(source, target).build().perform(); |
|
| 40. |
How to identify tooltip by using WebDriver? |
|
Answer» Tooltip is also known as the Help text. Tooltip is a text that appears when the mouse hovers over an object like a LINK, button image, etc. Sometimes it is a requirement of a project to address tooltip text. This tooltip text provides information RELATED to the object on which it appears. Objects have various attributes in HTML i.e object properties and one of them is “title” which contains tooltip text. SELENIUM’s purpose is to read that text of the object. Tooltip can appear in two ways - Static and Dynamic ways and both can be seen by mouse hover on the object. 1. Static Tooltip: Selenium can capture the Static tooltip by calling getAttribute(‘title’) method of WebElement and return the text of title which will be nothing but the tooltip. We will use the class attribute to make the image object(WebElement) and then we will use the getAttribute method. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class staticToolTip { public static void main(String[] args) { //Keep the chromedriver at project path location in eclipse System.setProperty("WebDriver.chrome.driver", System.getProperty("user.dir")+"/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://nikasio.com"); //Find the element by using class name WebElement edit = driver.findElement(By.id("header_logo")); String tooltiptext = edit.getAttribute("title"); System.out.println(tooltiptext); driver.quit(); } }2. Dynamic Tooltip: Dynamic Tooltip in applications is usually created by jQuery/javascript plugins. When we hover mouse on the object, tooltip object appears in HTML and as soon as the mouse is moved the object text DISAPPEARS. The getAttribute(‘title’) will not simply work. In the case of Dynamic tooltip, you have to use the ‘Actions class’ of Selenium. In the above image, you will see object related to this link but nothing for tooltip Once you will hover the mouse over the link, you will see a new entry in HTML(div tag ) which is nothing but the tooltip and when you will take the mouse out of the link, below div tag will disappear. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class dynamictoolTip { public static void main(String[] args) throws InterruptedException { System.setProperty("WebDriver.chrome.driver", System.getProperty("user.dir")+"/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://nikasio.com"); //Create object for link WebElement exampleLink = driver.findElement(By.class("avatar user-1-avatar avatar-150 photo")); //Create the Actions class Actions act = new Actions(driver); act.moveToElement(exampleLink).build().perform(); //Create object for inner div WebElement toolTip = driver.findElement(By.className("header_logo")); //Get the text of Tooltip String tooltiptext = toolTip.getText(); System.out.println(tooltiptext); driver.quit(); } } |
|
| 41. |
How to run only failed test cases? |
|
Answer» Many times test cases fail while running automated test scripts due to various reasons. It might be due to multiple reasons like network ISSUES, system issues or browser issues, etc. and we need to execute test scripts again using TestNG in Selenium. We can test these FAILED cases in two ways: Case 1: Execute failed test cases using TestNG in Selenium – By using “testng-failed.xml”
Case 2: Execute failed test cases using TestNG in Selenium – By Implementing TestNG IRetryAnalyzer. Create a class to implement IRetryAnalyzer. Here we create a class (say, RetryFailedTestCases) and implementing IRetryAnalyzer. package runfailedtestcases; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryFailedTestCases implements IRetryAnalyzer { private int retryCnt = 0; //You can ntioned maxRetryCnt (Maximiun Retry Count) as PER your requirement. Here if any failed testcases then it runs two times private int maxRetryCnt = 2; //This method will be called every time a test fails and will return TRUE if a test fails and need to be retried, else it returns FALSE public BOOLEAN retry(ITestResult result) { if (retryCnt < maxRetryCnt) { System.out.println("Retrying " + result.getName() + " again and the count is " + (retryCnt+1)); retryCnt++; return true; } return false; } }A simple implementation of this ‘IAnnotationTransformer’ interface can help you set the ‘setRetryAnalyzer’ for ‘ITestAnnotation’. Add the above class name (RetryFailedTestCases.class) in the below program. package runfailedtestcases; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.IRetryAnalyzer; import org.testng.annotations.ITestAnnotation; public class RetryListenerClass implements IAnnotationTransformer { @Override public void transform(ITestAnnotation testannotation, Class testClass, Constructor testConstructor, Method testMethod) { IRetryAnalyzer retry = testannotation.getRetryAnalyzer(); if (retry == null) { testannotation.setRetryAnalyzer(RetryFailedTestCases.class); } }We can evaluate the above example by simple tests Testcase 1: package runfailedtestcases; import org.testng.Assert; import org.testng.annotations.Test; public class Test1 { @Test public void test1(){ System.out.println("Test 1"); Assert.assertTrue(true); } }Testcase 2: package runfailedtestcases; import org.testng.Assert; import org.testng.annotations.Test; public class Test2 { @Test public void test2(){ System.out.println("Test 2"); Assert.assertTrue(false); } }As per the lines of code in Test2, it will fail. So Test2 will be executed 2 times as we took the maxRetryCnt as 2 in Retry Class. First, let us add the below-mentioned Listener to the testng.xml file. The below-mentioned syntax is to add Listener for RetryListnereClass subtext <listeners> <listener class-name="softwareTestingMaterial.RetryListenerClass"/> </listeners> Final testng.xml will look like below: <?xml VERSION="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="My Suite"> <listeners> <listener class-name="softwareTestingMaterial.RetryListenerClass"/> </listeners> <test name="Test1"> <classes> <class name="runfailedtestcases.Test1" /> </classes> </test> <!-- Test --> <test name="Test2"> <classes> <class name="runfailedtestcases.Test2" /> </classes> </test> <!-- Test --> </suite> <!-- Suite -->After executing testng.xml the output shows Test 2 is executed 3 times as we have mentioned “maxRetryCnt=2”. Even though we have just 2 test cases, we could see total test runs are 4 in the result. This way we could run failed test cases by applying TestNG in Selenium. |
|
| 42. |
What is WebDriverBackedSelenium? |
|
Answer» Selenium is a set of different software tools each with a different purpose and approach to supporting test automation. Selenium Webdriver is one of the tools in Selenium. The Java version of WebDriver SUPPORTS the IMPLEMENTATION of the Selenium-RC API. WebDriverBackedSelenium is a class name where you can create an object for it. The WebDriver API is fundamentally different in its design COMPARED to Selenium RC. You can use the WebDriver technology using the Selenium-RC API. This is MAINLY provided for backward compatibility. WebDriverBacked selenium allows you to use existing Selenium RC test suites using Selenium-RC API to use WebDriver under the cover. WebDriverBackedSelenium allows you to create tests with Selenium Remote Control syntax. String baseUrl = "https://nikasio.com"; String remoteControl = "localhost"; Int port = 4444; String browser = "*firefox"; Selenium selenium = new DefaultSelenium(remoteControl, port ,browser ,baseUrl); selenium.start(); selenium.open("/"); selenium.click("link=chapter1"); // rest of the test code WebDriverBackedSelenium is a class name where we can create an object for it as below: Selenium WebDriver= new WebDriverBackedSelenium(WebDriver objectName, “URL path of website”).The main purpose of this is when we want to write code using both WebDriver and selenium RC, we must use the above-created object to use selenium commands. |
|
| 43. |
What is Marionette, how does it work and when should you use it? |
|
Answer» For Mozilla’s GECKO ENGINE, Marionette is the web automation DRIVER. In the test automation developers community, it is also famous as the Gecko Driver. Marionette can control both the chrome i.e. menus and functions or the content of the webpage loaded inside the browsing context, giving a high level of control and ability to replicate user actions. Along with performing actions on the browser, Marionette can also read the properties and attributes of the DOM It has two modules, first is the server that accepts requests and executes and the second is a client to forward commands to the server. We use Marionette to run UI tests in the Firefox browser. A test automation engineer should add its dependencies to the framework, import the required classes and call the methods to control the web PAGE. Marionette also RETURNS the status of commands executed on the browser which can help in verifying the authenticity of the actions performed. |
|
| 44. |
What are the benefits does WebDriver has over Selenium RC? |
|
Answer» Selenium RC has a complex architecture whereas in WebDriver those complications are removed. Let us discuss why WebDriver is better than the RC. Selenium RC is slow because it uses an additional JAVASCRIPT LAYER known as the core and On the other hand, WebDriver is fast as it natively SPEAKS with the browser by UTILIZING browser's built-in engine to control it. The selenium core can not ignore the disabled elements while WebDriver handles the PAGE elements more realistic way. Selenium RC has a more mature set of APIs but contains redundancies and complicated and confusing commands. Whereas, WebDriver APIs his simpler and have a cleaner interface and do not have redundant and confusing commands. Selenium RC does not provide support headless HtmlUnit browser. It requires a real visible browser to operate on. On the other hand, WebDriver supports a headless HtmlUnit browser. Selenium RC includes a test result generator for HTML reports. Whereas WebDriver does not have any built-in reporting ability. |
|
| 45. |
What do you know about Selenese? |
|
Answer» Selenium IDE has a built-in linguistic system called Selenese. Selenese is a collection of Selenium commands to perform actions on a web page. Selenese can detect broken links on a page, or check the presence of a web element, AJAX, JavaScript alerts and a lot of many things. Mainly there are three types of command in Selenese.
|
|
| 46. |
How to send ALT/SHIFT/CONTROL key in Selenium WebDriver? |
|
Answer» When we use ALT/SHIFT/CONTROL keys, we hold onto those keys and click other buttons simultaneously to achieve the SPECIAL functionality. To hold onto these keys while SUBSEQUENT keys are pressed, you need to define two more methods: keyDown(modifier_key) and keyUp(modifier_key) Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONTROL) The purpose is to PERFORM a modifier key press and not to release the modifier key. Subsequent interactions may assume it’s kept pressed. Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONTROL) The purpose is to Perform a key release. With a combination of these two methods, you can capture the special function of a particular key. public static void main(String[] args) { String baseUrl = “HTTPS://www.facebook.com”; WebDriver DRIVER = new FirefoxDriver(); driver.get("baseUrl"); WebElement txtUserName = driver.findElement(By.id(“Email”); Actions builder = new Actions(driver); Action seriesOfActions = builder .moveToElement(txtUserName) .click() .keyDown(txtUserName, Keys.SHIFT) .sendKeys(txtUserName, “hello”) .keyUp(txtUserName, Keys.SHIFT) .doubleClick(txtUserName); .contextClick(); .build(); seriesOfActions.perform(); } |
|
| 47. |
Explain the statement WebDriver driver = new FirefoxDriver(); ? |
|
Answer» WebDriver is an Interface which is implemented by FirefoxDriver Class. FirefoxDriver is a class. It implements all the METHODS of WebDriver interface. It MAKES the reference of the interface and makes an OBJECT of FirefoxDriver so as to call implemented methods of WebDriver interface. We declare the left-hand SIDE variable as WebDriver and right-hand side to create an object for a particular type of the browser and ASSIGN it. WebDriver driver = new FirefoxDriver(); |
|
| 48. |
What is Selenese and different types of Selenese? |
|
Answer» Selenese is the set of selenium commands which are used for running the tests There are three types of Selenese :
|
|
| 49. |
Explain Desired capabilities in Selenium with one example? |
|
Answer» Desired CAPABILITIES is used to set properties for the WebDriver. It is also used to set the properties of browser such as to set BrowserName, Platform, Version of Browser etc. Example : STRING baseUrl , nodeUrl; baseUrl = "https:// https://www.seleniumhq.org/ "; nodeUrl = "http://192.168.10.21:5568/wd/hub"; DesiredCapabilities dcap = DesiredCapabilities.FIREFOX(); dcap.setBrowserName("firefox"); dcap.setPlatform(Platform.WIN10_1); driver = new RemoteWebDriver(new URL(nodeUrl),dcap); driver.manage().window().MAXIMIZE(); driver.manage().TIMEOUTS().implicitlyWait(30, TimeUnit.SECONDS); |
|
| 50. |
Explain Page Factory model in Selenium? |
|
Answer» Page Factory in Selenium is an extension to Page OBJECT Model and can be used to initialize web elements that are defined in web page classes or Page Objects. Page Factory will initialize every WebElement VARIABLE with a reference to a corresponding ELEMENT on the actual web page based on configured “locators”. This is done by using the annotation @FindBy. Example @FindBy(XPATH = "(//OPTION[text()='Basic auth'])[2]") private WebElement typeSctApp; |
|