Monday 2 October 2017

Selenium Super 30 Interview Questions - 3

21. How would you make sure that a particular feature is enable or disabled in the browser launched or how would launch a browser with some specific properties.
  • FirefoxProfile profile = new FirefoxProfile();
  • profile.setPreference("browser.startup.homepage", "http://www.google.com");
  • driver = new FirefoxDriver(profile);
22. What are the limitations with IE browser? What are the things that have to be done before actually using the IE browser for the automation?
·        If you see issue something like 'Unexpected error launching Internet Explorer' below, you have to set 'Enable protected mode' option in all levels with same value.
·        2. Make sure that the IE browser zoom level is set to 100% so that the native mouse events can be set to the correct coordinates.
·        3. It may be silly one, But make sure you provide correct path when setting the property of Internet explorer driver.
23. How would you locate a Frame without ID or Name?
  • WebElement frame = driver.findElement(By.xpath(<your frame xpath>));
driver.switchTo().frame(frame);
  • driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")))
24. Is it possible to migrate from selenium RC to Webdriver. Can I execute the scripts written in RC using webdriver. If yes how can we achieve the same?
Yes, it’s possible to migrate.
The first step when starting the migration is to change how you obtain your instance of Selenium. When using Selenium RC, this is done like so:
Java Code:
Selenium selenium = new DefaultSelenium(
    "localhost", 4444, "*firefox", "http://www.yoursite.com");
selenium.start();
This should be replaced like so:
Java Code:
WebDriver driver = new FirefoxDriver();
Selenium selenium = new WebDriverBackedSelenium(driver, "http://www.yoursite.com");
Next Steps
Once your tests execute without errors, the next stage is to migrate the actual test code to use the WebDriver APIs. Depending on how well abstracted your code is, this might be a short process or a long one. In either case, the approach is the same and can be summed up simply: modify code to use the new API when you come to edit it.
If you need to extract the underlying WebDriver implementation from the Selenium instance, you can simply cast it to WrapsDriver
Java Code:
WebDriver driver = ((WrapsDriver) selenium).getWrappedDriver();
This allows you to continue passing the Selenium instance around as normal, but to unwrap the WebDriver instance as required.
At some point, you’re codebase will mostly be using the newer APIs. At this point, you can flip the relationship, using WebDriver throughout and instantiating a Selenium instance on demand:
Java Code:
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
25. How to check if a text is highlighted on the page?
  • String color = driver.findElement(By.xpath("//a[text()='Shop']")).getCssValue("color");
  • String backcolor = driver.findElement(By.xpath("//a[text()='Shop']")).getCssValue("background-color");
  • System.out.println(color);
  • System.out.println(backcolor);
26. WebDriver is a class or interface? If interface name few of the methods which are part of the webdriver interface. Name the classes which have done the implementation from this interface.
WebDriver is Interface.
Methods: close(), findelememt(By by), findelemetns(By by), quit(), switchto() etc.
27. What is Page object Model? What is page factory? How would you initialize the webelements in Page Object Model?
     
·        Page Object Model is a design pattern to create Object Repository for web UI elements.
·        Under this model, for each web page in the application there should be corresponding page class.
·        This Page class will find the WebElements of that web page and also contains Page methods which perform operations on those WebElements.
Advantages of POM
·        Page Object Patten says operations and flows in the UI should be separated from verification. This concept makes our code cleaner and easy to understand.
·        Second benefit is the object repository is independent of testcases, so we can use the same object repository for a different purpose with different tools. For example, we can integrate POM with TestNG/JUnit for functional testing and at the same time with JBehave/Cucumber for acceptance testing.
·        Code becomes less and optimized because of the reusable page methods in the POM classes.
PageFactory
·        The PageFactory Class is an extension to the Page Object design pattern. It is used to initialize the elements of the Page Object or instantiate the Page Objects itself. Annotations for elements can also be created (and recommended) as the describing properties may not always be descriptive enough to tell one object from the other.
·        It is used to initialize elements of a Page class without having to use ‘FindElement’ or ‘FindElements’.
PageFactory.initElements(driver, PageName.class);
28. How would you count the number of rows of a given table?
·        //To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='SomeID']/div[1]/table/tbody"));
·        //To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
·        //To calculate no of rows In table.
int rows_count = rows_table.size();
29. Write the sequence of steps to delete a particular row (with user name = "xyz") in a table with multiple pages. One page contains max of 10 rows.
  
        Steps should include:
·        Locate the table
·        Locate the rows
·        Find a row with a user name “xyz”
·        If the user name is not present in the first page it should navigate to the next page
·        Repeat first 3 steps again till the row with username = “xyz” is found.
·        Delete the row.
 
30. Why do we need a Maven? What is the purpose of creating our own framework when selenium has already provided the APIs? Why do we need a framework?
Maven: Maven’s primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal there are several areas of concern that Maven attempts to deal with:
·        Making the build process easy
·        Providing a uniform build system
·        Providing quality project information
·        Providing guidelines for best practices development
·        Allowing transparent migration to new features
As part of the Automation framework it’s easy to add/update tools/APIs according to the latest versions available. We just need to configure the POM and build it. All the required jars will be added to the framework automatically.
Framework:
Automation framework is a way to organize your code in much meaningful manner, so that any person who is luckily working with you should understand what each file has and what is the purpose of adding the file.
A TEST Automation Framework is a set of guidelines like coding standards, test-data handling, object repository treatment etc., which when followed during automation scripting produce beneficial outcomes like increase code re-usability, higher portability, reduced script maintenance cost etc.

Selenium Super 30 Interview Questions - 2

 

11. Out of 100 check-boxes listed in the page you have to select a particular check-box with text = "abc". Sequence of check-boxes may change from time to time. Consider check-boxes and text in a tabular form.

One possible solution would be xpath:

selectCheckboxWithLabel(NameofLabel){

driver.findElement(By.xpath

        (".//*[@id='main']/table[1]/tbody/tr/td[2][text()=' NameofLabel ']//preceding-sibling::input[1]")).click

  }

12. Write the sequence of steps required to achieve the following:

In first window click on the link. This will open a new window. Enter some data into the text field and clicks submit. Close the second window and come back to the first window.

Click some button on first window and close it.

 Steps should include:

1.      Click on the link present on the main window

2.      Save the handler for the first window before switching to the new window.

3.      Switch to the new window.

4.      Enter some data on the text field and click submit

5.      Close the second window.

6.      Switch back to the main window before accessing any element on that window.

7.      Close the window.

13. Write the sequence of steps to access the element present in a Frame within a Frame.

                              WebElement OuterFrame = driver.findElement(By.id("Frame1")); 

                              //now use the switch command

                              driver.switchTo().frame(OuterFrame); 

                              //Find Frame2

                              WebElement InnerFrame = driver.findElement(By.id("Frame2"));

                              //now use the switch command

                              driver.switchTo().frame(InnerFrame);

                              //Switch back to the main window

                              driver.switchTo().defaultContent();

14. How to automate/capture the mouse hovering sequence. Write the steps

WebElement element = driver.findElement(By.linkText("Product Category"));

Actions action = new Actions(driver);

action.moveToElement(element).moveToElement(driver.findElement(By.linkText("linktext"))).click().build().perform();

15. How one can upload the file without using any external tool in selenium web-driver.

driver.findElement(By.xpath(“input field”)).sendKeys(“path of the file which u want to upload”);

16. Difference between web-based and window-based pop-up. How one can handle these pop-ups.

There are two types of alerts that we would be focusing on majorly:

1.    Windows based alert pop ups( Like Print Dialog )

2.    Web based alert pop ups (Alert box/ Pop up box/ confirmation Box/ Prompt/ Authentication Box)

As we know that handling windows based pop ups is beyond WebDriver’s capabilities, thus we need  some third party utilities to handle window pop ups(like Autoit, Robot etc.)

Handling web based pop-up box

WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.

There are the four methods that we would be using along with the Alert interface.

1) void dismiss()  The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
2) void accept()  The accept() method clicks on the “Ok” button as soon as the pop up window appears.
3) String getText()  The getText() method returns the text displayed on the alert box.
4) void sendKeys(String stringToSend)  The sendKeys() method enters the specified string pattern into the alert box.

 

Object Creation for Alert class:

v  Alert alert = driver.switchTo().alert();

We create a reference variable for Alert class and references it to the alert.

v  Switch to Alert
Driver.switchTo().alert();
The above command is used to switch the control to the recently generated pop up window.

v  Accept the Alert
alert.accept();
The above command accepts the alert thereby clicking on the Ok button.

v Reject the Alert
alert.dismiss();
The above command closes the alert thereby clicking on the Cancel button and hence the operation should not proceed.

17. How would you test a Captcha Code? Is it possible to test it?

Captcha code was introduced in order to prevent from the robot or automation codes. There is no option for automating the Captcha code.

v  You can give a wait time for the automation, so that the user can enter the captcha code.

v  If the project is in testing URL means, you can request your system admin and developer to disable the captcha validation.

Developers will generate a random value for captcha, and they will convert the value into image as well as they will store the value in session for comparing the entered input is matching with the captcha code.

So If possible, you can take that session value and give as the input.

Usually most of the companies either use their own captchas or one of the third party captchas (GooglejQuery plugins) in the user registration page of their sites .So these pages can't be automated fully. In fact Captcha itself is implemented to prevent automation. As per official captcha site

A CAPTCHA is a program that protects websites against bots  by generating and grading tests that humans can pass but current computer programs cannot.

Captchas are not breakable but there are some third party captchas that can be breakable and one of the example for it is "jQuery Real Person" captcha .

18. How would you take a screen shot for the failed test case? How does it work and where have you kept your code to capture the code in your framework?

In order to take screenshot in case of test failure we will use AfterMethod annotation of TestNG. In the AfterMethod annotation we will use ITestResult interface's getStatus() method that returns the test result and in case of failure we can use the above commands to take screenshot

@AfterMethod

public void takeScreenShotOnFailure(ITestResult testResult) throws IOException {

               if (testResult.getStatus() == ITestResult.FAILURE) { System.out.println(testResult.getStatus());

                              File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

                              FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));

    }

}

Location of this code depends on framework to framework. We need to dig more and get the design and location for screenshot based on their framework.

19. How are you reading the data from excel. Where are you keeping your data read from the excel when executing the test cases. How are you managing to execute the same test case with different set of data?

1.        FileInputStream fis = new FileInputStream(“path of excel file”);

    Workbook wb = WorkbookFactory.create(fis);

    Sheet s = wb.getSheet(“sheetName”);

    String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue();

2.      Depends on framework to framework how where and how candidates are storing the data. Whether its Array List or HashMap candidate should be able to explain their logic and write a dummy code for the same.

3.      Should explain Logic to execute same test case with different data or TestNG annotation to achieve the same functionality.

20. Difference between findelement and findelements. What are their return types?

  • findElement() method:

ü  We need to use findElement method frequently in our webdriver software test case because this is the only way to locate any element in webdriver software testing tool.

ü  findElement method is useful to locating targeted single element.

ü  If targeted element is not found on the page then it will throw NoSuchElementException.

  • findElements() method:

ü  We are using findElements method just occasionally.

ü  findElements method will return list of all the matching elements from current page as per given element locator mechanism.

ü  If not found any element on current page as per given element locator mechanism, it will return empty list.

 

 

Sunday 1 October 2017

Selenium Super 30 Interview Questions - 1

 

1.     Do you know how Ajax works? How you do make sure that the element is present after the Ajax Call.

               WebDriverWait wait = new WebDriverWait(driver, waitTime);

               wait.until(ExpectedConditions.presenceOfElementLocated(locator));

  2. How implicit wait works internally. What is the default value for implicit wait? 

v  Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.  

v  Being easy and simple to apply, implicit wait introduces a few drawbacks as well. It gives rise to the test script execution time as each of the command would be ceased to wait for a stipulated amount of time before resuming the execution.

·        implicitlyWait(10, TimeUnit.SECONDS);

v  The implicit wait mandates to pass two values as parameters. The first argument indicates the time in the numeric digits that the system needs to wait. The second argument indicates the time measurement scale. Thus, in the above code, we have mentioned the “30” seconds as default wait time and the time unit has been set to “seconds”.

v  While execution, if WebDriver cannot find element to act upon immediately, it will wait for specified amount of time.

v  During this time, no attempt is made to find an element. After completion of specified time, WebDriver will try to find an element once. Exception is displayed if element is not found after that. So, implicit wait should be kept low.         

v  The default setting is 0.

  3. What is the difference between implicit and explicit wait.

Implicit wait :

v  Defined for the entire life of the browser

v  If not found will not attempt to find till the time specified. i.e. no polling.

Explicit wait :

v  Defined for the particular element we are looking for.

v  Polls every 500 milli seconds by default.

v  Default polling 500 milliseconds

  4. If the implicit wait is set to 30 seconds, but the element is found within 5 seconds itself so in that case will that implicit-wait  wait for entire 30 seconds before moving to the next line?

               No, it will not attempt to find until 30 seconds.

  5. Based on the above answer if they tell something about polling then we can ask how implicit wait is different than explicit wait as polling happens in both cases.

               Implicit wait polls only twice. Explicit polls every 500 milliseconds.           

  6. WebDriverWait is a class or interface?

               Class, Refer documentation

  7. How Wait, FluentWait and WebDriverWait are related?

               interface Wait<WebDriver>

               class FluentWait<T> extends Object implements Wait

               class WebDriverWait extends FluentWait

     (Wait is an interface which is implemented by FluentWait. WebDriverWait extends FluentWait)

  8. Why we had to move to Selenium Web-Driver from selenium RC. What were the limitations in RC and how WebDriver has overcome them?

v  Selenium RC's architecture is quite complex as compare to WebDriver. WebDriver controls the browser from the OS level whereas If we are using Selenium RC's we first need to launch a separate application called Selenium Remote Control (RC) Server before you can start testing.

v  If we are using WebDriver all we need is our programming language's IDE (like Eclipse, which contains your Selenium commands) and a browser.

v  Let’s understand how Selenium works: The Selenium RC Server acts as a "middleman" between Selenium commands and the browser. When we execute our test cases from our IDE, Selenium RC Server "injects" a Javascript program called Selenium Core into the browser. Once injected, Selenium Core will start receiving instructions relayed by the RC Server from your test program. When the instructions are received, Selenium Core will execute them as Javascript commands. The browser will obey the instructions of Selenium Core, and will relay its response to the RC Server. The RC Server will receive the response of the browser and then display the results to you. RC Server will fetch the next instruction from your test script to repeat the whole cycle.

v  WebDriver is much faster than Selenium RC since it speaks directly to the browser uses the browser's own engine to control it. Selenium RC is slower since it uses a Javascript program called Selenium Core. This Selenium Core is the one that directly controls the browser, not you.

v  WebDriver mimics the behavior of actual human tester. If there is field which is disabled, it is disabled for the WebDriver as well and cannot be accessed, but this is not the case with RC, disabled field can be accessed usingRC.

v  WebDriver can support the headless HtmlUnit browser. Selenium RC cannot support the headless HtmlUnit browser. It needs a real, visible browser to operate on.

9. Difference between absolute and relative XPATH. Difference between / and //.

An absolute xpath in HTML DOM starts with html e.g.

html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the DOM element and generates xpath starting from that element e.g.

.//*[@id='answers']/h2[1]/a[1]

10. Suppose I have a text field with id = 12XYZ34, where 12 and 34 are dynamic and may change but XYZ will remain same. How would you locate the element in such case?

We can find elements using the following XPATH code.

·        XPath: //input[contains(@id, 'XYZ')] For 12XYZ34

·        XPath: //input[starts-with(@id, 'XYZ')] For XYZ34

·        XPath: //input[ends-with(@id, 'XYZ')] For 12XYZ

 

 

When Is The Birthday Of Cheryl ?













Puzzle 1: When is Cheryl's birthday?
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gives them a list of 10 possible dates.
         May       15    16    19
         June       17    18
         July        14    16
         August   14    15    17
Cheryl then tells Albert and Bernard separately the month and the day of her birthday, respectively.
Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know, too.
Bernard: At first, I didn't know when Cheryl's birthday is, but I know now.
Albert: Then I also know when Cheryl's birthday is.
So, When is Cheryl's birthday?

The answer to the Puzzle 1: 



This had been one of the famous puzzles on social media such as Facebook, Google+ and Twitter a few months back and become one of the commonly asked puzzles during interviews. Let's find out the solution:

Step 1:

First, you have to figure out what Albert knows that Bernard doesn't.

Cheryl gave the pair 10 possible dates. The combinations are made up of four possible months and dates falling between 14 and 19. Only 18 and 19 appear once across the 10 combinations.

If Bernard was told either 18 or 19, he would know Cheryl's birthday — either May 19 or June 18.

Albert says he doesn't know when Cheryl's birthday is, but neither does Bernard. If Cheryl had told Albert she was born in either May or June, it would be possible for Bernard to know when her birthday is (assuming she told him either 19 or 18). 

If Bernard can't know Cheryl's birthday with this information alone, we know Cheryl told Albert she was born in either July or August.


Step 2:

After Albert says his piece, Bernard announces he now knows when Cheryl's birthday is.

At this point, he has also been able to deduce the months down to July or August. From the potential dates in those two months, only 14 appears twice.

To know Cheryl's birthday, Bernard must have been told a number other than 14.


Step 3:

Albert then announces he also knows Cheryl's birthday, having eliminated two months and the number 14. This leaves him with three potential dates: July 16, August 15 and August 17.

If Cheryl had told Albert August, he would not know because he would still be missing the date — either 15 or 17.

Cheryl must have told Albert July, leaving him with only one possible date to celebrate his new friend's birthday: July 16.