Automation QA Testing Course Content

Broken images

package linkprograms;

package linkspograms;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrokenLinksTest {

private static WebDriver driver;

public static void main(String[] args) throws InterruptedException, IOException {
// set the chromedriver.exe path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome92\\chromedriver_win32\\chromedriver.exe");
// interface refvar = new browserclass();
WebDriver driver = new ChromeDriver();

// maxmize the window
driver.manage().window().maximize();

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

// open the https://makemysushi.com/404 website
driver.get("https://makemysushi.com/404");
List<String>ls=new ArrayList();
//fetch all the links in a browser
List<WebElement>linkList=driver.findElements(By.tagName("a"));
for(WebElement e:linkList) {
String url=e.getAttribute("href");
//adding each link url to the list collection
ls.add(url);
}
//removing unwanted urls from the collection using removeAll()
ls.removeAll(Arrays.asList(null,"mailto:info@makemysushi.com"));
//validate each link by validateLinks()
for(String s:ls) {
validateLinks(s);
}
//close the browse
driver.close();
}
private static void validateLinks(String url) throws IOException {
//create Object for URL class
URL ul = new URL(url);
HttpURLConnection hc= (HttpURLConnection) ul.openConnection();
//connect to the url
hc.connect();
//fetch the status code of the url
int respStatusCode=hc.getResponseCode();
String respMsg=hc.getResponseMessage();
if(respStatusCode==200) {
System.out.println(url+" is working fine:"+respStatusCode+" "+respMsg);
}else if(respStatusCode==404) {
System.out.println(url+" is not working/broken:"+respStatusCode+" "+respMsg);
}
//disconnect from the url
hc.disconnect();
}

}




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.