Selenium Questions Part6: Scenario Based and Some Tricky Questions

1. There is a scenario whenever “Assert.assertEquals()” function fails automatically it has to take screenshot. How can you achieve this?

Answer: Please refer below link

https://www.automationtestinginsider.com/2020/04/how-to-capture-screen-shot-for-failed.html

2. Open a browser in memory, means whenever it will try to open a browser the browser page must not come and can perform the operation internally?

Answer:

use HtmlUnitDriver. Please refer below program.

ex-

public class Memory

{

public static void main(String[] args)

{

HtmlUnitDriver driver = new HtmlUnitDriver(true);

driver.setJavascriptEnabled(false);

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

driver.get("https://www.google.co.in/");

System.out.println(driver.getTitle());

}

}

Please refer below link for more details info on headless browsers

https://www.automationtestinginsider.com/2020/04/selenium-headless-browser-testing.html

3. How will you handle dynamic web tables when you don’t have any idea on the number of rows or columns will be displayed every-time?

Answer:  Please refer the complete post below on how to handle dynamic web table:

https://www.automationtestinginsider.com/2020/04/handle-dynamic-webtable-in-selenium.html

4. What are the different types of waits, write their syntax, differences and explains the example scenarios where you have used in your Selenium Projects?

Answer:  Please refer below link on waits

https://www.automationtestinginsider.com/2020/02/waits-in-selenium-webdriver.html

5. in a web page, how will you ensure that the page has been loaded completely?

Answer:  While automating any application using Selenium Web Driver, we may come across some situations where we have to wait for the page to load completely, before performing any actions on any elements on the page. In order to understand how to wait for the complete page to load before performing any activities, go through the below explanation:

We can execute the JavaScript code having document.readyState parameter to check whether the ‘complete’ status of the page is returned or not.

Example for using the above specified JavaScript code in Selenium for ensuring the completeness of page loading: The below reusable user defined method can be called anytime you want to check the completeness of page loading:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Pageloadtest {

                static WebDriver driver;
                public static boolean waitForPageLoad(WebDriver driver, int timeout) {
                                ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
                                                public Boolean apply(WebDriver driver) {

                       return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");

                                  }
                                };
                                WebDriverWait wait = new WebDriverWait(driver, timeout);
                                boolean flag=wait.until(pageLoadCondition);
                                return flag;

                }
                @Test
                public void pageLoadTest() {
                                WebDriverManager.chromedriver().setup();
                                driver = new ChromeDriver();
                                driver.manage().window().maximize();
                                driver.get("https://www.espncricinfo.com/");
                                System.out.println("PageLoad Test: "+waitForPageLoad(driver, 40));
                                driver.close();

                }

}

We can call the above method using the following method calling statement:

waitForPageLoad(driver, 40); //waits till page load gets completed by setting a time limit of 40 seconds

6. What will you do if there are failures in your suite execution and what is your approach?

Answer: While executing the automation scripts, test cases may fail for several reasons. To optimize our next runs, we need to re-run only failed test cases. How to execute failed Test cases? What is the best approach? In TestNg class, we can easily re-run the test cases using two methods as explained below:

Method 1:  By using testng-failed.xml file in test-output folder.

Method 2:  By implementing TestNG IRetryAnalyzer.

Please refer below link to look for complete details:

https://www.automationtestinginsider.com/2020/03/run-failed-test-cases-in-selenium.html

7. Through Actions class can you pass the test data like instead of sendkeys?

Answer: Yes we can do that, please refer below link

https://www.automationtestinginsider.com/search/label/Keyboard%20operations%20in%20selenium

8. What difference you see when working with different browser?(except set up or configuration level)?

Answer: below are the few differences we can see across working with different browsers:

  • Font size mismatch in different browsers.
  • JavaScript implementation can be different.
  • CSS,HTML validation difference can be there.
  • Some browser still not supporting HTML5.
  • Page alignment and div size.
  • Image orientation.
  • Browser incompatibility with OS. Etc.

9. How to reduce page load time? if any particular data taking some time?

Answer: The script performance is better with explicit waits as HTML elements are accessed as soon as they become available.

One of the best ways of making a script faster is by using only explicit waits. If your test scripts uses delays and implicit waits like this,

WebDriver driver = new FirefoxDriver();

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

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

WebElement myElement=driver.findElement(By.id(“myElement”));

Replace them with explicit waits.

Syntax:

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

WebDriver driver = new FirefoxDriver();

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

WebElement element = (new WebDriverWait(driver, 10))

.until(ExpectedConditions.presenceOfElementLocated(By.id(“element”)));

10. Your script performing some actions on a list elements in between if page get refreshed, how to handle the situation?

Answer:  I think that kind scenario related to a page which has an ajax poll and automatically refreshes when some condition is reached on the server.

In this scenario you could wait for the Ajax request to finish. That way you don't concern yourself if the page is loaded. You continue after the ajax request is done.

Please refer below link on waits.

https://www.automationtestinginsider.com/2020/02/waits-in-selenium-webdriver.html

11. How would you enable a disabled textbox?

Answer:  You can enable a disabled html control(like, input, textarea, button,...) with the help following code.

To disable:

document.getElementById("id_name").setAttribute("disabled", true);

To enable:

document.getElementById('id_name').removeAttribute('disabled');

Example:

//To enable Last Name text box

  String toenable = "document.getElementsByName('lname').removeAttribute('disabled');";

  javascript.executeScript(toenable);

  Thread.sleep(3000);

12. How to do you continue execution when stops in middle?

Answer: use soft assertions org.testng.asserts.SoftAssert. Soft assertions are assertions that do not terminate the test when they fail but their results are included in the test execution report.

https://www.automationtestinginsider.com/2020/03/assertions-in-testng.html

13. Can you open cmd promt using wedriver?

Answer:  Yes, please refer below program

public class OpenCMD
{
public static void main(String[] args)
    {
        try
        { 
                Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"java -version\"");
        }
        catch (Exception e)
        {
            System.out.println("Something went wrong");
            e.printStackTrace();
        }
    }
}

14. Suppose there is one method in interface as private and a class is implementing. Can implemented method be public or vice versa?

Answer: In interface only public, abstract, default, static modifiers are permitted

15. When we don't want to create object of the class?

Answer: We don’t need to create the object of static methods; Static methods belong to the class and thus don’t require it to be instantiated. Although, you can create its object and then also use those methods, but creating a class for static method is of no use.

16. There are four browser windows opened and you don’t have any idea where the required element is present. What will be your approach to find that element?

Answer: Please refer below link on handling multiple windows

https://www.automationtestinginsider.com/2020/02/handle-multiple-windows-in-selenium.html

17. Tell me any difficulties you faced in developing automation scripts? Can you give any examples for any complex scenarios handled?

Answer:  Sync issue or Timeout

Example: After clicking on some button one alert should present and we have to handle via code but due to many issues alert might come after a few seconds, in that case, the script will fail. We need to handle this kind of scenario using an explicit wait. This is just one example like this we have many examples which show without a smart locator we cannot build stable scripts.

Smart locators

As we all know that locators are the core part of any scripting and we need to keep on enhancing our XPath and CSS for script stability, because if XPath and CSS are not proper then chances are very hight that script might fail in upcoming releases.

We should always write dynamic or custom XPath or class, which can make our script more stable.

Cross browser testing

While designing script we always focus on one browser and we design our script for that browser only, but when it comes to real execution of the script then we have to make sure that our script should run in all browser which is known as Cross Browser Testing (Chrome, FF, IE at least). I had been struggling with this topic , because few locators will work in one browser but not on the other. In order to avoid failure once the script is developed we need to run them on the different browsers and analyse the result. If it is failing on another browser then we need to change locator strategy.

Pop up handling

In many applications, you will find random pop that keeps coming and their behaviour is not persistent, so we also have to take care of these unwanted pop up which stops our execution.

When Code Review is not done

Many companies they do not follow proper code review which can create many issues in the future.

Example- Code review includes code formatting, proper validation or assertion, effective usage of the framework, the design pattern used and so on.

Some code review tools:

  • Checkstyle
  • PMD
  • FindBugs

18. If you execute the scenarios in your project multiple times, will the reports override? If they override, how will you take backup of previous test report?

Answer: You can override reports. You can create your file name to be the current timestamp. This way, it will be easy to have a unique name for your report file -

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

htmlReporter= new ExtentHtmlReporter (System.getProperty("user.dir") +"\\test-output\\" + timeStamp + ".html");

19. Suppose I clicked on 4 links in a page, 4 new windows got opened. How to switch to 4th window from main window?

Answer:  Please refer below link on handling multiple windows

https://www.automationtestinginsider.com/2020/02/handle-multiple-windows-in-selenium.html

20. Try block has exit method, catch block has exception and finally block is returning an int value. Can you explain the flow of execution?

Answer:  finally block will be executed no matter what even if try block throws any throwable(exception or error)

Only case finally block does not execute is when we call System.exit() method.

public class NewClass
{
           public static int test()
    {
        try {
            System.out.println("try");
            System.exit(1);
        } catch(Exception e) {
            System.out.println("catch");
        } finally { 
            System.out.println("finally");
            return 1;
        }
    }
public static void main(String[] args)
    {
                test();
}
}

Output

try

21. There are 3 classes say A,B and C in your project. How to access the methods of B and C from A Class?

Answer:  Please refer below program

ClassC
public class ClassC {
                public void methodC() {
                                System.out.println("ClassC");
                }
}
ClassB
public class ClassB extends ClassC {
                public void methodB() {
                                System.out.println("ClassB");
                }
}
ClassA
public class ClassA{
               public static void main(String[] args) {
                                ClassB objB= new ClassB();
                                objB.methodB();
                                objB.methodC();
                }
}

Output:

ClassB

ClassC

22. What will you do when you have more number of lines of code having repeated code?

Answer:  We can avoid the duplicate code by using custom methods, Inheritance etc.

23. In Selenium project, we use hierarchy like interface, followed by abstract class, followed by a class. Can’t we directly use interface followed by a class?

Answer: Yes we can do that; in that case we need to implement all the methods from interface in the class which implements the interface.

24. in a page, if we have 3 apply buttons (1st button on top, 2nd button in middle and 3rd button on the bottom). How will you click on the middle button?

Answer:  Please refer below example for xpath and then perform click operation.

Xpath: //button/span[text()='Search'][2]

25. What is the problem with Thread.Sleep in code?

Answer:

1) It is a Static wait: If given a wait of 5000 Milliseconds(5 seconds) and an element just take just 1-2 seconds to load, script will still wait for another 3 seconds which is bad as it is unnecessarily increasing the execution time. So thread.sleep() increases the execution time in cases where elements are loaded in no due time.

2) When using Thread.sleep(), we have to mention wait time in advance, there is no guarantee that the element will be displayed in that specific wait time, there may be case when it will takes may be more than 5 seconds to load and again the script would fail.

3) You need to write sleep() method whenever we need to make webdriver wait. So if you want to wait for two web elements, you need to write Thread.sleep() twice just before you locate web elements.

4) It is not good programming practice. Instead you can use implicit or explicit waits.

26. Manually you opened a Firefox browser window with Gmail login, now with selenium you opened a Firefox browser window with Facebook login, what happens when we use quit method? Will it closes all windows including Gmail one?

Answer:  No it will not close manually opened windows.

27. There are two methods in same class with same name with different arguments and different access modifiers like

public void m1(int a)

{

}

private void m1(string b)

{}

 Is it overloading or not?

Answer:  Yes it is an example overloading

Two methods will be treated as overloaded if both follow the mandatory rules below:

Both must have the same method name.

Both must have different argument lists.

And if both methods follow the above mandatory rules, then they may or may not:

Have different return types.

Have different access modifiers.

Throw different checked or unchecked exceptions.

28. There are 10 pages in same window; an image is present in any page out of ten pages in same window. How will you validate this scenario?

Answer:  Please refer below program to handle such scenario:

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandle1 {
                public static void main(String[] args) throws InterruptedException {
                                WebDriver driver;
                                System.setProperty("webdriver.chrome.driver",
              "C:\\Users\\Hitendra\\Downloads\\chromedriver_win32 (2)\\chromedriver.exe");
                                driver = new ChromeDriver();
                                driver.manage().window().maximize();
                                // To open Naukri.com with multiple windows
                                driver.get("https://www.naukri.com/");
                                Thread.sleep(2000);
                                // It will return the parent window name as a String
                                String parentWinID = driver.getWindowHandle();
                                System.out.println("Parent Win ID is: " + parentWinID);
                                // It returns no. of windows opened by WebDriver and will return Set of Strings
                                Set<String> allWinID = driver.getWindowHandles();
                                System.out.println("Total Window size:" + allWinID.size());
                                System.out.println("All win IDs are:");
                                for (String allIDs : allWinID) {
                                                System.out.println(allIDs);
                                }
                                // Using Iterator to iterate with in windows
                                Iterator<String> itr = allWinID.iterator();
                                while (itr.hasNext()) {
                                              String childWinID = itr.next();
                                                // Compare whether the main window is not equal to child window. If not equal,
                                                // we will close child windows.
                                               if (!parentWinID.equalsIgnoreCase(childWinID)) {
                                                              driver.switchTo().window(childWinID);

                                                                try {

//Verify this image present on LNT window

                                                                                WebElement hsbcImg = driver.findElement(By.xpath("/html/body/a/img[@alt='LnT']"));

                                                                                if (hsbcImg.isDisplayed()) {

                                                                                                System.out.println("LnT img present: " + hsbcImg.isDisplayed());

                                                                                }

                                                                } catch (Exception e) {

                                                                                e.printStackTrace();

                                                                }

                                                                System.out.println("Child URL is:" + driver.getCurrentUrl());

                                                                System.out.println("Child Win Title is:" + driver.getTitle());

                                                                Thread.sleep(2000);

                                                                driver.close();

                                                }

                                }
                                // This is to switch to the main window
                                driver.switchTo().window(parentWinID);
                                driver.quit();

                }

}

29. How to check whether an image is loaded correctly or not in page?

Answer:  You can check if the image is displayed or not by using the interface, JavaScriptExcecutor.

Object result = ((JavascriptExecutor) driver).executeScript(

   "return arguments[0].complete && "+
   "typeof arguments[0].naturalWidth != \"undefined\" && "+
   "arguments[0].naturalWidth > 0", image);
    boolean loaded = false;
    if (result instanceof Boolean) {
      loaded = (Boolean) result;
      System.out.println(loaded);
    }

You can use this code to Pass the image (WebElement)-

You can actually verify if the image is loaded on the webpage

30. Given a scenario that 5 test cases are there I need to execute first and last 3 (means 2 should not be executed) ? How u make changes in testng xml file?

Answer:  Let’s say we have a class NewClass and this class has five test methods (Test1, Test2, Test3, Test4, and Test5).

Without using annotation, we can skip few cases in selenium testing by following the script in testng Suite

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite">

  <test thread-count="5" name="Test">

    <classes>

      <class name="package.NewClass">

      <methods>

      <include name="Test1"></include>

      <include name="Test3"></include>

      <include name="Test4"></include>

      <include name="Test5"></include>

      <exclude name="Test2"></exclude>

      </methods>

      </class>

    </classes>

  </test> <!-- Test -->

</suite> <!-- Suite -->

Two more ways are given below:

First method is to setup the condition enabled or disabled in Test annotation.

@Test(enabled=true)

Second method is to setup the group details at Test annotation.

@Test(group = {functionalTest} )

31. How do you verify that the given list of numbers on a web page is sorted in ascending order?

Answer:  Please refer the below program

First Way:

public class OrderTest {
                @Test
                public void test() {
                               List<Integer> integers = new ArrayList<>();

        integers.add(5);
        integers.add(10);
        integers.add(0);
        integers.add(-1);
        System.out.println("Original list: " +integers);
        Collections.sort(integers);
        System.out.println("Sorted list: "+integers);

                }

}

Output

Original list: [5, 10, 0, -1]

Sorted list: [-1, 0, 5, 10]

Second Way:

public class OrderTest {
                @Test
                public void test() {
                                Set<Integer> set= new TreeSet<Integer>();
                                set.add(5);
                                set.add(10);
                                set.add(0);
                                set.add(-1);
        System.out.println("Sorted list: "+set);
                }

Output:

Sorted list: [-1, 0, 5, 10]

32. We have 65,000 URLs which we release 3 times a day. How will you test using selenium?

Answer:  keep 6500 urls and destination page in 10 excel sheet (10X6500=65000) use threads and run the web driver code to check URL present in each sheet.

33. We have 2 interfaces and both have print methods, in my class I have implemented the print method , how you will get to know that I have implemented the first interface and how you will use it .. if you want to use it?

Answer: if a type implements two interfaces and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.

34. How to automate charts using xpath? Need to extract the value from pie chart with appropriate legend and compare with backend?

Answer:  Please refer the below program for reference.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class ChartTest {

                static WebDriver driver;

                public static void main(String[] args) {

                                WebDriverManager.chromedriver().setup();

                                driver= new ChromeDriver();

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

                                driver.get("http://yuilibrary.com/yui/docs/charts/charts-pie.html");

                                //Locate pie chart elements based on different colors.

                                  WebElement VioleteColor = driver.findElement(By.xpath("//*[contains(@class,'yui3-svgSvgPieSlice')][@fill='#66007f']"));

                                  WebElement GreenColor = driver.findElement(By.xpath("//*[contains(@class,'yui3-svgSvgPieSlice')][@fill='#295454']"));

                                  WebElement GreyColor = driver.findElement(By.xpath("//*[contains(@class,'yui3-svgSvgPieSlice')][@fill='#e8cdb7']"));

                                  WebElement LightVioleteColor = driver.findElement(By.xpath("//*[contains(@class,'yui3-svgSvgPieSlice')][@fill='#996ab2']"));

                                  WebElement BrownColor = driver.findElement(By.xpath("//*[contains(@class,'yui3-svgSvgPieSlice')][@fill='#a86f41']"));

                                  //locate tooltip pie chart.

                                  WebElement ToolTip = driver.findElement(By.xpath("//div[contains(@id,'_tooltip')]"));

                                  //Click on pie chart parts and get tooltip values.

                                  System.out.println("-X-X-X-X-X-X-X-X- Violete Part -X-X-X-X-X-X-X-X-");

                                  VioleteColor.click(); 

                                  System.out.println(ToolTip.getText());

                                  System.out.println(); 

                                  System.out.println("-X-X-X-X-X-X-X-X- Grey Part -X-X-X-X-X-X-X-X-");

                                  GreyColor.click();

                                  System.out.println(ToolTip.getText());

                                  System.out.println();

                                  System.out.println("-X-X-X-X-X-X-X-X- Light Violete Part -X-X-X-X-X-X-X-X-");

                                  LightVioleteColor.click();

                                  System.out.println(ToolTip.getText());

                                  System.out.println();

                                  System.out.println("-X-X-X-X-X-X-X-X- Green Part -X-X-X-X-X-X-X-X-");

                                  GreenColor.click();

                                  System.out.println(ToolTip.getText());

                                  System.out.println();

                                  System.out.println("-X-X-X-X-X-X-X-X- Brown Part -X-X-X-X-X-X-X-X-");

                                  BrownColor.click();

                                  System.out.println(ToolTip.getText());               

                }

}

35. User have 50 frames, want to click a button inside 25th and 49th frame?

Answer: Please refer below link about iframes

https://www.automationtestinginsider.com/2020/02/handling-iframes-in-selenium-webdriver.html

36. If an explicit wait is 10 sec and the condition is met in 5 sec, will driver move to execute next statement after 5 sec or it will wait for complete 10 sec then move?

Answer: driver will move to next statement after 5 seconds.

More about waits: https://www.automationtestinginsider.com/2020/02/waits-in-selenium-webdriver.html

37. If element is loaded by taking much time, how to handle this situation in selenium?

Answer: Apply fluent wait.

More about waits: https://www.automationtestinginsider.com/2020/02/waits-in-selenium-webdriver.html

38. If xpath on a dev server got changed write a single xpath which will work in both dev/prod

39. 1000 screens (Pages) in your application?.. which framework you would use?

40. Want to store 10000 elements in a collection which collection to use?

41. First time test case passed second time aborted. What could be the reason?

42. How to access phone number from 1000 pages?

43. How to put 2 sec of wait after each line of code without thread.sleep?

44. If you want to run the test script in diff browser with time differences How to do that?

45. Write a Java code to copy the emp id from the first excel sheet having emp name and emp id, and paste copied emp name into another excel sheet have emp name only based on the emp name?

46. I want to take one test case report from all the executed test cases. How can we get it without using TestNG?

47. Suppose 400 test cases are running and after 150 test cases got executed the system got crashed or network was gone or application got crashed. How to run only the test cases which are not executed?

48. There are 300 test cases, I want to execute test cases in some custom order, how to change the order of execution without doing changes in testng.XML and in code(.class files). If we can do, tell the logic and if we cannot do, justify with reason?

49. Is default polling frequency 250 ms applies to implicit wait or explicit wait or for both types of wait?

50. If submit button is contained in one of 3 frames in page, how will you handle this case?

51. Excel sheet contains 5 rows with id name and attribute. Delete the first row which contains previous data?

52. Write code for Google search and finding no of results?

53. How to test google map?

Please refer below YouTube video to understand the explanation of above Q/A



8 comments:

  1. HI,
    When you publish the answers

    ReplyDelete
  2. Answer please all the scenario questions

    ReplyDelete
  3. wow.. these kind of questions now a days asked by interviewer , author plz publish answer or make vedeo in channel...i can realize answers some qustions...need help to others

    ReplyDelete
  4. I'm following your YouTube channel and your website...I'm waiting for these questions answeres and explanation

    ReplyDelete
  5. First time test case passed second time aborted. What could be the reason?
    Possible causes:
    1. Network Issue
    2. Changes in application (in case there was a build in between 2 runs) OR application issue (not stable)
    3. Manual error - like data setup was not done correctly or altogether missed, typo error etc
    4. application (or any component) is down
    5. data error or business validation / error not handled in the automation TC (like expectation is unique data but script enter duplicate data)
    6. Unknown error -
    7. Script issue - not able to handle multiple validation cases (e.g dynamic xpath) or not compatible with multiple browsers.
    8. test dependency error (TC 1 dependent on TC2, and we are directly running TC2).
    etc...
    8. synchronization issue

    ReplyDelete
  6. 44. If you want to run the test script in diff browser with time differences How to do that?
    // not exactly sure, but 1 suggestion on the question
    you can add a delay like if the browser is chrome then add a initial delay of 0/1 secs, if the browser is firefox add a intial delay of 5 secs, this way both your threads for the test script will run in parallel but due to the condition 1 TC will wait for 0/1 sec and start the exe, however the 2nd with firefox will wait for 5 secs before staring. let me know if this soln is right?

    ReplyDelete