我正在使用selenium webdriver
+ TestNG
。如果可能,请帮助我解决以下问题:有没有办法在循环中使用断言来查找页面
搜索页面上所有损坏的图像并在测试失败后在控制台中显示它们(使用声明)。
下面的测试失败,首先被分解图像后发现,我需要测试,以检查所有图像,并显示结果当它失败:
public class BrokenImagesTest3_ {
@Test
public static void links() throws IOException, StaleElementReferenceException {
System.setProperty("webdriver.chrome.driver", "/C: ...");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://some url");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Find total Number of links on page and print In console.
List<WebElement> total_images = driver.findElements(By.tagName("img"));
System.out.println("Total Number of images found on page = " + total_images .size());
//for loop to open all links one by one to check response code.
boolean isValid = false;
for (int i = 0; i < total_images .size(); i++) {
String image = total_images .get(i).getAttribute("src");
if (image != null) {
//Call getResponseCode function for each URL to check response code.
isValid = getResponseCode(image);
//Print message based on value of isValid which Is returned by getResponseCode function.
if (isValid) {
System.out.println("Valid image:" + image);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
} else {
System.out.println("Broken image ------> " + image);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
}
} else {
//If <a> tag do not contain href attribute and value then print this message
System.out.println("String null");
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
continue;
}
}
driver.close();
}
//Function to get response code of link URL.
//Link URL Is valid If found response code = 200.
//Link URL Is Invalid If found response code = 404 or 505.
public static boolean getResponseCode(String chkurl) {
boolean validResponse = false;
try {
//Get response code of image
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(chkurl);
HttpResponse response = client.execute(request);
int resp_Code = response.getStatusLine().getStatusCode();
System.out.println(resp_Code);
Assert.assertEquals(resp_Code, 200);
if (resp_Code != 200) {
validResponse = false;
} else {
validResponse = true;
}
} catch (Exception e) {
}
return validResponse;
}
}
在这种情况下,我经常将无效映像的src属性附加到字符串构建器,并声明其长度为零,并将构建器的内容用作消息的一部分。这样你就可以在日志中获得更具体的内容。 –
如果你像这样遍历一个'WebElement'的列表,你可能会得到一个陈旧的元素。 –
@PeteKirkham这些无效图像将不包含空的src。 CSS选择器将其过滤掉。这些更多的是不存在的图像或不合适的URL。任何失败都会使其IMG标记的完整HTML被记录下来。 – JeffC