有没有办法在循环中使用断言来查找页面上所有损坏的图像

时间:2017-02-16 12:31:28

标签: java selenium selenium-webdriver testng

我正在使用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;
    }
}

3 个答案:

答案 0 :(得分:2)

您的代码在第一次失败时停止的原因是因为您使用Assert使resp_Code等于200.TestNG将在第一次失败的断言上停止执行。

我会这样做有点不同。您可以使用CSS选择器仅使用src查找包含"img[src]"属性的图片,这样您就不必处理该案例。当我查找损坏的图像时,我使用naturalWidth属性。如果图像被破坏,它将为0。使用这两个部分,代码看起来像......

List<WebElement> images = driver.findElements(By.cssSelector("img[src]"));
System.out.println("Total Number of images found on page = " + images.size());
int brokenImagesCount = 0;
for (WebElement image : images)
{
    if (isImageBroken(image))
    {
        brokenImagesCount++;
        System.out.println(image.getAttribute("outerHTML"));
    }
}
System.out.println("Count of broken images: " + brokenImagesCount);
Assert.assertEquals(brokenImagesCount, 0, "Count of broken images is 0");

然后添加此功能

public boolean isImageBroken(WebElement image)
{
    return !image.getAttribute("naturalWidth").equals("0");
}

我只写出破碎的图像。我更喜欢这种方法,因为它使日志更清洁。写image会写出一些不会有用的乱码,所以我改为编写外部HTML,它是IMG标签的HTML。

答案 1 :(得分:0)

assertEquals()投掷AssertionError,而不是Exception。如果代码在您的情况下不相等,它将抛出AssertionError,您的测试将停止并完成为失败。 如果您在Error中抓住Exception而不是catch(),它应该可以按预期工作。

答案 2 :(得分:0)

作为JeffC的附录,我更喜欢收集错误的src属性并将其报告为失败而不是记录到单独的文件,例如:

List<WebElement> images = driver.findElements(By.cssSelector("img[src]"));
System.out.println("Total Number of images found on page = " + images.size());
StringBuilder brokenImages = new StringBuilder();
for (WebElement image : images)
    if (isImageBroken(image))
        brokenImages.append(image.getAttribute("src")).append(";");
Assert.assertEquals(brokenImages.getLength(), 0,
    "the following images failed to load", brokenImages);

(只有答案,因为用代码解释比在评论中更容易解释)