Saturday, 22 October 2016

Selenium Test to Check Links in Web Page are working

Testing all the links inside a web page is working fine or not is most important testing scenario. We can test this scenario very easily with selenium. As we know the links will be inside html tag <a> we can use By.tagName("a") locator and use an iterator in java to make the process simple.

This Simple example will help you perform various types of testing like -

1. Testing broken links on webpage using selenium.
2. Clicking on a link or click on all links on  web page to verify links are working fine.
3. Counting number of Links on web page.
4. Getting List of Links on web page.
5. Find out list of non working links on webpage.

Example -

Consider we want to test all links in homepage of

Test Case -

Check out below test case and read the descriptions mentioned in the comment section to understand the flow.

package selenium.tests;

import java.util.List;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;

public class TestAllLinks { 
 public static void main(String[] args) {
        String baseUrl = "";
        WebDriver driver=new ChromeDriver();
        String notWorkingUrlTitle = "Under Construction: QAAutomated";
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        List<WebElement> linkElements = driver.findElements(By.tagName("a"));
        String[] linkTexts = new String[linkElements.size()];
        int i = 0;

        //extract the link texts of each link element
        for (WebElement elements : linkElements) {
            linkTexts[i] = elements.getText();

        //test each link
        for (String t : linkTexts) {
            if (driver.getTitle().equals(notWorkingUrlTitle )) {
                System.out.println("\"" + t + "\""
                        + " is not working.");
            } else {
                System.out.println("\"" + t + "\""
                        + " is working.");

Output -

"Home" is working fine
"About Me" is working fine
"Contact Us" is not working ....

If you find this useful please share the post with your friends using share options given below. You can write your feedback and suggestion in the comment section.

1 comment:

  1. When Executed above code i have encountered this erorr-Exception in thread "main" org.openqa.selenium.WebDriverException: Element is not clickable at point (104.5, 30). Other element would receive the click:
    Command duration or timeout: 87 milliseconds