QA WBA 3 Sprint Summary

Modified on Mon, 24 Jul, 2023 at 10:35 AM

Index:


  • Xpath

  • Web-Driver-Manager

  • TestNG


Topic 1: Xpath


Xpath



What is it? 

XPath (XML Path Language) is a query language used for selecting nodes from an XML document, and is widely used in Selenium WebDriver for locating elements in a webpage.



Where is it used? 

XPath is used in Selenium WebDriver for identifying and interacting with web elements based on their attributes, hierarchical position, or both.



How to capture Xpath?

XPath expressions can be manually written or generated using browser's developer tools. Here are steps to capture XPath using Chrome:



  • Open your web application in Chrome.

  • Right click on the element you want to capture the XPath for.

  • Click on "Inspect" to open Chrome Developer Tools.

  • Right click on the highlighted code in the "Elements" panel.

  • Go to "Copy" and then click "Copy XPath". This copies the XPath to your clipboard.



Types of Xpath

Absolute XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed. It starts with the root node.



Relative XPath: For this, the path starts from the middle of the HTML DOM structure. It starts with the double forward slash (//), which means it can search the element anywhere at the webpage.



Syntax of Xpath

XPath contains path expressions to select nodes or node sets in an XML document. The nodes are selected by following a path or steps, for example:


  • Selects all nodes with the name "nodename": nodename

  • Selects from the root node: /

  • Selects from the current node: .

  • Selects attributes: @


Dynamic Xpaths

Dynamic XPaths are used in cases where the attributes of an element are dynamic or change with every session. Here is an example of how to create dynamic XPath:

//WebElement that contains attribute with dynamic values

driver.findElement(By.xpath("//input[starts-with(@id,'user-')]"));



This will find the input element whose id starts with `user-`.


Takeaways / best practices

  • XPath can be a powerful tool for identifying elements on a webpage, particularly for complex or dynamic webpages.

  • Relative XPaths are generally preferable as they're more resilient to changes in the webpage structure.

  • Be careful with long or overly complex XPath expressions as they can be hard to read and maintain.

  • While you can generate XPaths using browser tools, understanding the XPath syntax will allow you to create more robust and efficient identifiers.

Chained Xpath



Chained Xpath



What is it? 

Chained XPath is a methodology in XPath where multiple XPath expressions are combined to identify a specific web element uniquely.



Where is it used? 

Chained XPath is used in scenarios where a single XPath expression is not enough to identify an element uniquely. This method becomes useful when dealing with complex or dynamic web pages where web elements are not easily identifiable by simple identifiers.



How is it used?


Chaining involves using more than one XPath expression to navigate through elements and their relationships in the DOM:

  • Identify the parent element using an XPath expression.

  • From the parent, create another XPath expression to identify the child element.


For example:

//First, find the parent element

WebElement parent = driver.findElement(By.xpath("//div[@id='parent']"));

//Then, find the child element within the parent

WebElement child = parent.findElement(By.xpath(".//div[@id='child']"));




Xpath Axes

What is it? 

XPath Axes are methods used in XPath expressions to identify complex or dynamic elements based on their relationship with other elements in the DOM.



Where is it used? 

XPath Axes are used in scenarios where identifying an element based on its attributes is not feasible or the attributes are not unique. They are especially helpful when the element's position in the DOM hierarchy in relation to other elements is more constant.



How is it used? and Code snippet

There are several different types of XPath Axes methods like ancestor, child, descendant, following, parent, preceding, self, etc. Here's an example of how to use the 'following' XPath Axes method:

//Find the first input element that follows a specific div

driver.findElement(By.xpath("//div[@id='unique_div']//following::input[1]"));



Takeaways / best practices 

  • Chained XPaths and XPath Axes provide more flexibility for identifying elements but can also lead to more complex identifiers. Always strive for the most straightforward, reliable identifier possible.

  • XPath Axes allow for powerful navigation possibilities, but remember that using these methods can lead to more complex and slower performing XPath expressions. Be judicious in their use.

  • Avoid chaining too many XPath expressions together, as this can lead to brittle tests that are highly sensitive to changes in the DOM structure.

  • As with any identifiers, make sure your XPath expressions (whether simple, chained, or using axes) uniquely identify the intended element on the page.




Topic 2: Web-Driver-Manager


Web Driver Manager


What is it?

WebDriverManager is a library that allows to automate the management of the binary drivers (like chromedriver, geckodriver, etc.) required by Selenium WebDriver for web automation.



Where is it used?

WebDriverManager is used in automation testing where Selenium WebDriver is used for browser-based testing. It simplifies the management of binary drivers for different browsers.



Setting up Web Driver Manager on your machine

Add WebDriverManager as a dependency in your build.gradle file:


dependencies {

    testImplementation 'io.github.bonigarcia:webdrivermanager:4.4.3'

}



Before creating the instance of WebDriver (like ChromeDriver, FirefoxDriver, etc.), just call the WebDriverManager setup method.

Here is an example:


WebDriverManager.chromedriver().setup();

WebDriver driver = new ChromeDriver();


In the above lines of code, WebDriverManager will check the version of the browser installed in your machine (Chrome in this case) and download the compatible WebDriver binary (chromedriver.exe) if it's not already available in your system or if it's not up to date.



Advanced settings of WDM

WebDriverManager provides advanced settings like using a specific version of the driver, ignoring versions, and using mirror sites for downloading drivers, among other things.



Here's an example of setting a specific version:

WebDriverManager.chromedriver().driverVersion("2.40").setup();


HTML Unit Driver

HTML Unit Driver is a headless browser driver, meaning it doesn't have a user interface. This makes it lightweight and faster, making it suitable for tasks that don't require user interaction and just need to fetch information from web pages.



Takeaways / best practices 

  • WebDriverManager is a handy tool that simplifies the setup of WebDriver instances, making your tests easier to write and less reliant on specific system configurations.

  • While it's useful for most cases, there might be scenarios where you need to manually configure your WebDriver instance (like for using a specific version of the driver).

  • HTML Unit Driver can speed up your tests significantly but doesn't support JavaScript as well as regular browsers, so it might not be suitable for all testing scenarios.



Topic 3: TestNG


Testing Frameworks - TestNG



Need for a testing framework



What is it? 

A testing framework is a set of guidelines or rules used for creating and designing test cases. It includes coding standards, object repositories, test-data handling methods, and processes to store test results.



Where is it used? 

Testing frameworks are used in software testing to ensure the application under test meets the business requirements. They are typically used in automation testing to provide a systematic approach to testing, ensuring consistency, and improving test efficiency.



How is it used? 

  • Select a suitable testing framework based on the project requirements.

  • Design the test cases following the guidelines of the testing framework.

  • Execute the test cases using the testing framework.

  • Analyze the results as per the framework's reporting features.



TestNG



What is it?

TestNG (Test Next Generation) is a testing framework inspired from JUnit and NUnit, but it introduces some new functionalities that make it more powerful and easier to use.


Where is it used?

TestNG is used in the field of automated software testing, especially while working with Selenium for automating web applications.


How is it used?


  • Add TestNG dependency to your project.

  • Create a new test class.

  • Use TestNG annotations like @Test, @BeforeSuite, @AfterSuite etc.




import org.testng.annotations.*;


public class TestNGExample {


    @BeforeSuite

    public void setup() {

        System.out.println("Setup for the test suite");

    }


    @Test

    public void testCase1() {

        System.out.println("Executing Test Case 1");

    }


    @AfterSuite

    public void cleanup() {

        System.out.println("Cleanup after the test suite");

    }

}


Annotations in Java



What is it?

Annotations in Java are tags that represent metadata associated with class, interface, methods, or variables.


Where is it used?

Annotations are used in Java to provide additional information about the program that is not part of the program itself. They are used by the compiler and JVM to provide useful behavior during compile and runtime, respectively.


How is it used? and Code snippet


  • Declare the annotation before the item you're annotating (like a method).

  • Specify any parameters the annotation requires.



@Override

public String toString() {

    return "This is a custom toString method";

}


Takeaways / best practices 


  • Choose a testing framework that best suits your project requirements, considering factors such as language compatibility, reporting features, and community support.

  • In TestNG, utilize the variety of annotations provided to control the flow and order of your test cases.

  • Use Java annotations to control the behavior of your program. They can be extremely powerful, but they can also introduce complexity, so use them judiciously.

  • Always maintain your test code with the same level of discipline as your production code. Good practices like code reviews, version control, and continuous integration should also apply to your tests.


TestNG annotations


What is it? 

TestNG Annotations are lines of code that control how methods and classes are executed in TestNG. They provide metadata about the test script to TestNG.



Where is it used? 

They are used in test scripts written with the TestNG testing framework.



How is it used? 

TestNG supports several important annotations like:


  • @Test: Marks a class or a method as a part of the test.

  • @BeforeMethod and @AfterMethod: Executes before and after every @Test method.

  • @BeforeClass and @AfterClass: Executes before and after the class is instantiated in the test script.

  • @BeforeSuite and @AfterSuite: Executes before and after a suite of tests is run.

  • @Test Annotation Attributes




What is it?

The @Test annotation in TestNG has several attributes (like enabled, timeOut, etc.) that help to control the test method's execution.



How is it used?

Here are some commonly used attributes:


  • enabled: It is a boolean attribute. If set to false, the @Test method will not be executed.

  • timeOut: The number of milliseconds TestNG will wait before marking the test as failed.

  • expectedExceptions: The list of exceptions that a test method is expected to throw.




@Test(enabled = false)

public void testCase1() {

    // This test will not run

}


@Test(timeOut = 1000)

public void testCase2() {

    // This test will fail if it takes longer than 1 second to finish

}


@Test(expectedExceptions = ArithmeticException.class)

public void testCase3() {

    // This test will pass if an ArithmeticException is thrown

    int division = 1 / 0;

}


Using testng.xml File



What is it?

The testng.xml file in TestNG is used to define test suites and test cases. It provides a centralized place to configure your tests.



How is it used?

  • Create a file named testng.xml.

  • Define your test suites, tests, classes, and methods in the XML structure.




Here's an example of a testng.xml file:


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

<suite name="AllTests">

    <test name="LoginTests">

        <classes>

            <class name="com.mycompany.LoginTest" />

        </classes>

    </test>

</suite>


Emailable Reports



What is it? 

Emailable reports are a feature of TestNG that generates a summarized test report in HTML format which can be emailed.



Where is it used? 

Used in TestNG to share test results with the team.



How is it used? 

After running the TestNG tests, an HTML file named 'emailable-report.html' is automatically generated in the 'test-output' folder. This can be emailed to stakeholders.



Takeaways / best practices 


  • Leverage TestNG annotations to control the flow and execution of your tests.

  • Use the @Test annotation attributes to further refine your test methods.

  • Use the testng.xml file to organize and manage your test cases and suites.




Assertions and Data Parameterization



Assertions



What is it? 

Assertions in TestNG are used to verify the correctness of the test's outcome, essentially determining whether the test passed or failed.



Where is it used? 

Used in TestNG to verify the result of a test execution.



How is it used? 

TestNG supports hard assertions (default) and soft assertions. Hard assertions halt the test execution if they fail, while soft assertions continue with the test execution regardless of their result.

@Test

public void test() {

    Assert.assertEquals(actualResult, expectedResult);

}


Data Parameterisation



What is it? 

Data Parameterisation is the process of running the same test case(s) multiple times with different data sets.



Where is it used? 

Used in testing when the same scenario needs to be validated with different sets of data.



How is it used? 

In TestNG, this can be done using the @Parameters annotation or @DataProvider.



@Test

@Parameters({"username", "password"})

public void test(String username, String password) {

    // Test code here

}



Data Providers



What is it?

Data Providers in TestNG are methods that return a collection of objects to the test method. The test method will then be invoked once per entry in the collection.



Where is it used?

Used in TestNG to provide data for a test method.


How is it used?


@DataProvider(name = "loginData")

public Object[][] getData() {

return new Object[][]{{"user1", "pass1"}, {"user2", "pass2"}};

}


@Test(dataProvider = "loginData")

public void test(String username, String password) {

// Test code here

}



Listeners


What is it?

Listeners in TestNG are interfaces that allow certain actions to be taken every time certain events occur in a test script.


Where is it used?

Used in TestNG to perform specific actions when an event is invoked.


How is it used?

TestNG provides several listener interfaces, like ITestListener, IReporter, etc. Users can implement these interfaces to create their own listeners.


public class CustomListener implements ITestListener {


    @Override

    public void onTestStart(ITestResult result) {

        // Code to execute when the test starts

    }


    // Other methods to override...

}


Takeaways / best practices 

  • Use Assertions to validate the expected output of your test cases.

  • Data Parameterisation allows you to execute your test cases with different sets of data, increasing coverage.

  • Data Providers provide an efficient way to provide different parameters to a test method.

  • Implement Listeners in your test scripts to perform actions based on specific events. This can be particularly useful for things like logging and taking screenshots on test failures.



All the best and Happy Learning!

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article