Cucumber

What is Cucumber?

  • Definition: Cucumber is an open-source tool that supports BDD.
  • Purpose: Bridges the communication gap between business stakeholders and developers by using plain language.
  • Language: Uses Gherkin language for writing test cases

Key Features of Cucumber

  • Human-Readable Format: Test scenarios are written in plain language, making them understandable by non-technical stakeholders.
  • Gherkin Language:
    • Structure: Given-When-Then syntax.
  • Ex:
                Scenario: User logs in successfully
                      Given the user is on the login page
                      When the user enters valid credentials
                      Then the user should be redirected to the dashboard

  • Integration: Compatible with various programming languages (Java, Ruby, Python, etc.).
  • Automation: Facilitates automated testing by linking Gherkin steps to code.
  • Benefits of Using Cucumber

    • Collaboration: Encourages collaboration between developers, testers, and business analysts.
    • Clarity: Clear and concise test cases improve understanding of requirements.
    • Traceability: Each scenario can be traced back to user stories or requirements.
    • Reusable Steps: Gherkin steps can be reused across multiple scenarios, reducing redundancy.

    Best Practices for Using Cucumber

    • Keep Scenarios Short: Focus on specific behaviours.
    • Use Backgrounds: Share common steps across multiple scenarios.
    • Avoid Technical Jargon: Write steps in plain language for clarity.
    • Maintain Step Definitions: Keep them clean and organized to avoid duplication.
    • Regular Reviews: Regularly review and update scenarios to match changing requirements.

    Common Challenges and Solutions

    • Ambiguous Steps: Avoid by making steps specific and clear.
    • Maintenance Overhead: Mitigate by organizing feature files and step definitions.
    • Performance Issues: Optimize test execution by focusing on critical scenarios and using tags to group tests.


    Listeners

     1. What are the listeners of selenium?

    1. It is an interface
    2. WebDriverListener is one of the interfaces which contain a method of selenium events.

    3. We can use listeners to track events of the script during the execution
    4. Can use them to log special information as below
    5. Log info about script start and end
    6. Log info about script execution duration
    7. Log info about script pass-fail details

     2. Provide a few abstract methods in WebDriverListner interface

    1. beforeQuit(WebDriver driver) - This method will be called before WebDriver.quit() is called.
    2. beforeSubmit(WebElement element) - This action will be performed each time before WebElement.submit() is called.
    3. onError(Object target, Method method, Object[] args, InvocationTargetException e) - Notifies registered listeners about an error that occurred during the execution of a decorated method.
    4. afterClose(WebDriver driver) - This method will be called after WebDriver.close() is called.

    Log Info

     1. What frameworks or libraries are commonly used for logging error information in Java applications?

    1. Log4j
    2. SL4J

    2. What types of log levels and messages can be recorded using Log4j?

    1. info
    2. error
    3. debug
    4. warn
    5. fatally

    Screen Shot

     1. How can I capture screenshots using Selenium WebDriver?

    1. Use getScreenShotAs() method
    2. It is in the TakesScreenShot Interface
    3. create reference of TakesScreenShot interface. 
    4. Get the screen shot using getScreenShotAs().
    5.  By default it will store screen shots in temp folder. 
    6. Create destination to store the file using File class. 
    7. Copy the file from src to destination using copyFile() of FileUtils class
    File scrFile =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

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

    2. Can you explain how to capture and save a screenshot using Selenium WebDriver?

    We can use the TakeScreenshot function to capture the screenshot and the getScreenshotAs() command to save the screenshot.

    CSS Selectors

     1. How to locate dynamic elements in selenium?

    For dynamically changing elements needs to use locators like XPath or CSS locators. So then it is possible to locate the element using stable part of attributes or parent elements

    1. Locate using parent elements
    2. locate using child elements
    3. locate using ancestor elements
    4. locate using descendant elements
    5. Locate using sibling elements
    6. Locate using stable half of the value, id, name or text attributes using starts-with and contains keywords

    2. What are the types of selectors supported by Selenium?

    1. id
    2. CSS
    3. class name
    4. XPath
    5. link Text
    6. partial link text
    7. name
    8. tagName

    3. What are the advantages of using CSS selectors?

    1. It is a more human-readable format
    2. Well suited for identifying elements based on their classes, id, types, attributes

    4. What are the cons of using CSS selectors?

    1. Limited to identify elements based on their relationship like, parent, child, sibling etc…
    2. Cannot traverse in both directions both up and down

    5. Identify elements using CSS selectors

    1. tagName[attributeName = ‘attributeValue’]
    2. tagName#idValue
    3. tagName.classValue

    6. What is link text?

    text available inside <a> tags called link text

    <a href="ForgotPassword.php">Forgot Password?</a>
    Text: >Forgot Password?<

    //element locator
    By.linkText("Forgot Password?")
    By.partialLinkText("Forgot")

    7. What are the tag names of the table?

    1. tr -> table row : By.tagName(“tr”)
    2. td-> table data: By.tagName(“td”)
    3. th-> table header

    8. What are the components of HTML?

    1. text
    2. attributes
    3. tags

    9. How to find all the links on a web page?

    1. Using anchor tag (a)
    List<WebElements> list = driver.findLements(By.tagName(‘a’));

    10. What is the difference between ID and name locators?

    id: is unique on the given page. so it is easy to identify elements.

    name: name is not unique. multiple items can share the same name.


    Limitations

     1. What are the limitations of Selenium?

    • Only web applications can be tested using Selenium
    • mobile applications cannot be tested with selenium
    • Captcha and barcode readers cannot be tested using Selenium
    • Need third-party tools like TestNG to generate reports
    • Prior programming knowledge is needed
    • Configurations and set-up are complex
    • It is not possible to automate mobile apps

    2. What is CAPTCHA?

    1. CAPTCHA is likely a security feature that distinguishes between human and automated bots.
    2.  It provides challenges that can be solved by human visual interaction and it is hard to solve by automated scripts.
    3. Automating CAPTCHA is not ethical and illegal

    3. Is that possible to automate the captcha using selenium?

    No

    4. Using third-party tools is that possible to automate captcha?

    There can be ways to automate. But it is not ethical and illegal.

    5. Does selenium support bar code reading?

    1. No.
    2.  Selenium is designed for automated web testing and there are no built-in functions to read barcodes.
    3.  Barcode reading requires external libraries or tools

    6. What are the external libraries that support reading barcodes?

    Zebra Crossing

    Authentication Pop up

     1. How to handle authentication pop-ups?

    1. Embed the credentials in the URL String url = “http://www.username:password.com”
    2. Use a Web driver with an 
    alert alert.sendKeys(“username” + Keys.TAB + “password”) ; alert.accept()
    1. Use ChromeOptions (Browser capabilities)

    2. How to handle the basic authentication alerts?

    1. To handle basic authentication pop-ups in Selenium, where a username and password are required to access a URL, you can use the Alert interface.
    2.  However, please note that basic authentication pop-ups are not traditional JavaScript alerts, so you'll need to use a different approach.
    3. Download and Install AutoIT
    4. Create an AutoIT Script:
    • Write an AutoIT script (e.g., BasicAuth.au3) to handle the authentication pop-up. Save the script with the following content
    WinWaitActive("Authentication Required")
    Send("your_username{TAB}your_password{ENTER}")

    5. Compile the AutoIT script to an executable (.exe) file using the AutoIT compiler.

    6. Run selenium code

    import org.openqa.selenium.WebDriver;


    import org.openqa.selenium.chrome.ChromeDriver;

    public class BasicAuthExample {
    public static void main(String[] args) {
    // Set the path to the ChromeDriver executable
    System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

    // Create an instance of the ChromeDriver
    WebDriver driver = new ChromeDriver();

    // Navigate to the URL with basic authentication
    driver.get("https://username:password@the-internet.herokuapp.
    com/basic_auth"
    );

    // Your further Selenium actions go here

    // Close the browser
    driver.quit();
    }
    }

    3.How to handle Windows-based pop-ups?

    driver.switchTo().window()

    4. How to handle Windows pop-ups?

    Use third-party plugins like AutoIT. 

    Window & Frame

     1. What does the switch command use?

    The switch is used to switch between windows, frames, pop-ups…

    2. Write code to switch between multiple Windows

    driver.switchTo.window(handle)
    for(String handle : driver.getWindowHandles()){
    driver.switchTo.window(handle)}

    3. How to maximize the window?

    driver.manage.window.maximize();

    4. How to handle multiple tabs and windows in Selenium?

    using getWindowHandles() method

    5. Difference between getWindowHandle() and getWindowHandles() methods?

    1. windowHanlde is a unique identifier.
    2. getWindowHandle(): return single handle. A String value
    3. getWindowHandles(): Return set of handles: Set of String values

    6. How to switch between multiple tabs?

    driver.switchTo().window(windowHandle)

    7. What does window handle mean?

    It is a unique identifier of each window. It is a String value. It can be used to switch between tabs.

    8. What is an iframe?

    1. It is called an inline frame. 
    2. they are HTML documents embedded within other HTML documents.

    9. How to automate iframe-related scenarios?

    1. need to use switchTo() method as below
        driver.switchTo().frame();

    10. How to come back to the main content once iframe functionalities are done?

    1. need to switch back to the main frame
    driver.switchTo().frame();
    ...

    driver.switchTo().defaultContent(); or

    driver.switchTo().parentFrame();

    11. What parameters can be passed inside the frame() method?

    1. frame(index)
    2. frame(name)
    3. frame(id)
    4. frame(WebElement)

    WebElement Interface

     1. What is meant by WebElement?

    1. WebElement is an Interface provided by Selenium to identify HTML elements in the web page. 
    2. It provides methods to interact with web elements such as clicking, entering text etc..

    2. How do you verify the element is present?

    driver.findElement(By.tagName(‘row’)).isPresent();

    3. What is an element?

    An element is an object represented in a web page.

    4. Element Locating Mechanism

    1. These are static methods
    2. By is an Abstract class
    3. All the methods argument type is String
    1.By.id();
    2.By.name();
    3.By.className();
    4.By.tagName();
    5.By.linkText();
    6.By.partialLinkText();
    7.By.xpath();
    8.By.cssSelector();

    5. Can you explain how you can handle colours in a web driver?

    1. We can use the command getCSSValue(arg0) to fetch the colours by sending the colour as the argument
    2. It is a method in WebElement Interface
    3. These are the properties: background, font, border, border-top, margin, margin-top, padding, padding-top, list-style, outline, pause, cue
    driver.findElement(By.id('id')).getCssValue(String css property)
    //Get the value of a given CSS property

    6. What are the methods of web elements?

    1. click()
    2. clear()
    3. sendKeys()
    4. getCssValue() : To get the colour/size/font of the particular
    5. getText()
    6. getAttribute()
    7. isDisplayed()
    8. isSelected()
    9. getTagName() : To get the tagname of particular webelement
    10. getSize()
    11. getLocation():To get the X-axis and Y-axis location particular web element
    12. isEnabled()
    13. submit(): To click on an element only if the type of the element is submitted Ex: <input type=” submit” id=”s” value=”Submit”>

    7. John is not sure if the warning text label is displayed on the web page of a blog. How will you help him using Selenium?

    We can use the method isDisplayed() to confirm the presence of the element on the screen.

    Boolean buttonPresence = driver.findElement(by.id("sample").isDisplayed();

    8. What is the difference between getText() and getAttribute() methods?

    1. getText(): it returns the text of the selected element.
    driver.findElement(“elementLocator”).getText();

      2. getAttribute(): it returns the value of the attribute in a given element.

    driver.findElement(By.className("row"))getAttribute("value" or "name", "id" etc…)

    9. How to verify that the element is displayed on the web page?

    Using isDisplayed() method. It returns a true or false Boolean value.

    driver.findElement(By.id(‘row’)).isDisplayed();

    10. How to check web element is enabled for interaction?

    driver.findElement(element).isEnabled();

    It returns a Boolean value true or false.

    11. How to locate a link using its text?

    1. Use linkText() or partialLinkText()
    driver.findElement(By.linkText(“hey”));

    12. How to extract the value of the tooltip text?

    1. The web page uses the ‘title’ attribute to keep the tooltip text
    2. We can fetch the value from the title attribute using the below way
    String tooltip = driver.findElement(By.id('row')).getAttribute('title')

    13. How to select a radio button using a selenium web driver?

    driver.findElement(radioBtn).click();

    14. How to check on the checkbox?

    driver.findElement(By.id(“row”)).click();

    15. How to submit a form using selenium?

    1. Use the submit() method or click on the submit button element.


    WebDriver Interface

     1. What are the WebDriver methods?

    1. get()
    2. getTitle()
    3. getCurrentURL()
    4. findElement()
    5. findElements()
    6. getWindowHandle()
    7. getWindowHandles()
    8. manage()
    9. close()
    10. quit()
    11. navigate()
    12. switchTo()
    13. getPageSource()

    2. What is the use of driver.getPageSource() method?

    It is used to get the source code of the page. It returns a String that contains the HTML source code of the page. 

    1. It can be used for assertions
    2. It is used for data extraction
    3. It is used for security testing
    4. How our page web page is structured
    5. How our web elements are presented

    3. How to get the title of the current page?

    String title = driver.getTitle()

    4. How to close a specific tab?

    driver.close();

    5. What is the difference between driver.close() and driver.quit() methods?

    1. driver. close(): close the current window. If there are multiple windows are opened it will close only the currently focused window
    2. driver.quit(): quit from the driver. Quit from the associated window as well.

    6. What is the difference between findElement and findElements options?

    findElement: this returns the first element which matches the given selecting mechanism. if it can’t find anything it returns NoSuchElementExecpetion.

    findElements: this returns a list of an element that matches the given selecting mechanism. If there is nothing to find it returns an empty list

    7. How can we launch different browsers in Selenium WebDriver?

    System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");

    // Create a new instance of the FirefoxDriver
    WebDriver driver = new FirefoxDriver();
    // create a new instance of chrome driver
    Webdriver driver =. new ChromeDriver();

    8. We need to test the responsiveness of the UAT in different browser screen sizes. Can this be done in Selenium?

    1. Yes.
    2. Use Dimension class in Selenium
    int width = 600;
    int height = 400;
    Dimension dimension = new Dimension(int width, int height);
    driver.manage().window().setSize(dimension);

    2. window.resizeTo() method and capability commands can also be used to achieve the same result. Use windows.resizeTo() method along with Javascript executor.

    ((JavascriptExecutor)driver).executeScript(“window.resizeTo(600,400);”);

    9. How to set a position?

    //WebDriver.Window interface profide setPosition(Point targetPosition)
    //above method
    //It Set the position of the current window
    //It takes argument as object in Point class

    Point point = new Point(300,200);
    driver.manage().window().setPosition(point);

    11.Write a code to launch the browser

    public static void main(String[] args){

    WebDriver driver;
    System.setProperty("webdriver.chrome.driver","C:/Users/Driver/chromedriver");
    driver = new ChromeDriver();
    driver.get("url");
    driver.close();
    }

    12. Write code to launch the browser based on user input

     public static void launchBrowser(){

    Scanner scanner = new Scanner(System.in);
    WebDriver driver = null;
    System.out.println("Enter browser name: ");
    String browser = scanner.nextLine();

    if(browser.equals("chrome")){

    System.setProperty("webdriver.chrome.driver","C:/Users/Driver/chromedriver");
    driver = new ChromeDriver();
    driver.get("url");
    }

    else if(browser.equals("firefox")){

    System.setProperty("webdriver.gecko.driver","C:/Users/Driver/firefoxdriver");
    driver = new ChromeDriver();
    driver.get("url");
    }
    else {
    System.out.println("Wrong name name should be firefox or chrome");
    }
    scanner.close();
    }

    13. What is By class?

    1. It is provided by WebDriver API
    2. It provides static methods to locate elements
    3. id(), className(), name(), tagName(), XPath() etc…

    14. How to get the current URL of a page?

    driver.getCurrentUrl();

    15. Explain the below line

    WebDriver driver = new FirefoxDriver();

    WebDriver is an interface. We are creating an object from type as WebDriver and instantiating the new object from the FirefoxDriver class. It has access to all the methods in the WebDriver interface. In the future, if the class is changed there is only one place we have to change

    16. Why create a driver reference variable from the WebDriver interface?

    So we can use it for creating instances from other classes like ChromeDriver, GecoDriver etc…

    17. What is HtmlUnitDriver?

    1. HtmlUniDriver is the fastest web driver. 
    2. Unlike other (Chrome, firefox etc…) drivers this is non-GUI.
    3.  So it executes on headless mode. 
    4. So the browser is not visible during the execution.

    18.Why do we use headless drivers?

    1. speed and efficiency
    2. Resources efficiency
    3. Server side execution
    4. Reduce flakiness — graphical rendering of web pages causes issues
    5. It provides more stable and predictable test results

    19. How can you visually investigate failures if use a headless driver?

    1. Logging and console output
    2. We can use Log4j or SL4J
    3. Add listeners to take screenshots when the test fails

    Alerts

     1. What are the characteristics of JavaScriptAlerts?

    • We can not move the pop-up. 
    • We can not inspect the popup. 
    • It is black and white 
    •  If it contains only the ok button then it is an alert pop-up. 
    • If it contains only the ok and cancel buttons, it is a confirmation pop-up.
    • If it contains only the Text box, ok and cancel button then it is a prompt pop-up
    2. What is an alert on the web page?

    1. they are normally pop-up dialogue boxes which appear with a message.
    2. it contains information which users need to interact with.
    3. There are 3 types of javascript alerts
    4. Alert (one OK button and message)
    5. Confirmation (OK and cancel button with the message)
    6.  Prompt (input field with OK and Cancel buttons)
    3. How do you handle alerts in Selenium?

    1. Selenium provides an Alert interface to interact with the alerts. 
    2. first, we must switch to alert using the driver.switchTo().alert().
    3. Then we can use several methods call accept(), dismiss(), getText()

    4. Explain what is accept() and dismiss()?

    accept(): used to accept the alert by clicking the OK button.

    dismiss(): used to dismiss the alert by clicking on the cancel button.

    5. How to verify text in the alert?

    Using the getText() method. it retrieves the text of the message in an alert box.

    6. How to send data in prompt alert?

    using the sendKeys() method we can pass the value we want to send as information in the alert box.

    7. How to verify the presence of an alert?

    • Use the WebDriverWait class 
    •  use the alertIsPresent() method in ExpectedConditions class.

    8. Can you switch from one alert to another?

    1. You cannot
    2.  first, switch into alert and then switch back to the main window. 
    3. then again switching to alert is the way.
    9Can you handle or disable alerts at the browser level?

    No. Selenium cannot handle browser-level alerts. it needs third-party plugins or capabilities.

    10. Write Code to click the ok button, cancel button, send data and get the text value of an alert

    driver.switchTo().alert().accept();
    driver.switchTo().alert().dismiss();
    driver.switchTo().alert().sendKeys(input value);
    driver.switchTo().alert().getText();

    11. You need to retrieve the message in an alert box, without using the getText() method. How will you handle this situation in Selenium IDE

    1. storeAlert() command can be used to retrieve the message from the alert pop-up
    2. The value is stored in a variable that can be returned using a System.out.println statement. 
    3. You can also use assertEquals() to verify this message
    4. The command will read the alert text and store it in a specified variable.storeAlert(variable_name) 
    5. This is used in Selenium IDE 

    Cucumber

    What is Cucumber? Definition : Cucumber is an open-source tool that supports BDD . Purpose : Bridges the communication gap between business ...