【问题标题】:Selenium WebDriver - two part - 1) Fail test on AssertEquals failure 2)Verify Element not presentSelenium WebDriver - 两部分 - 1) AssertEquals 失败测试失败 2) 验证元素不存在
【发布时间】:2012-07-21 16:32:47
【问题描述】:

我带着更多愚蠢的问题回来了

1) 如果 AssertEquals 为 false,如何使测试失败?

我有这个代码 -

public boolean compareWidthPixels(By by, String expected) {
    System.out.println(driver.findElement(by).getCssValue("width"));
    try {
        assertEquals(expected, driver.findElement(by).getCssValue("width"));
        System.out.println("Width as expected");
        return true;

    } catch (Error e) {
        verificationErrors.append(e.toString());
        System.out.println("Width incorrect");
        return false;

    }

当宽度与预期值不匹配但测试用例通过时,此代码显示“宽度不正确”。如果宽度不相等,我希望测试失败。

2) 如何断言/验证元素不存在?

作为一个新手,我尝试了很多我在 Google 和 Stack Overflow 中找到的东西 - Assert that a WebElement is not present using Selenium WebDriver with javaSelenium WebDriver - Test if element is present 等。但它们都不起作用。我正在使用 JUnit4 并且需要一个在元素不存在时应该通过的函数。

谢谢

弥勒

P.S:如果它看起来令人困惑或迷失方向,请随时编辑此问题。

【问题讨论】:

  • 看看下面的答案。至于为什么会发生这种情况,您正在捕捉异常 - 所以测试运行者不会意识到一个被提升并因此相信它通过了。有几种断言方法,包括 assertTrue 和 assertFalse:junit.sourceforge.net/javadoc/org/junit/Assert.html

标签: java selenium selenium-webdriver junit webdriver


【解决方案1】:

答案 1:要使用断言 true 或 false,您应该使用 if else 代替,然后通过断言调用函数,例如

public boolean compareWidthPixels(By by, String expected) {
    System.out.println(driver.findElement(by).getCssValue("width"));
    if (driver.findElement(by).getCssValue("width").equals(expected)){
        System.out.println("Width as expected");
        return true;
    } 
    System.out.println("Width incorrect");
    return false;
}

然后在您的测试中使用 compareWidthPixels 作为 'AssertTrue(compareWidthPixels(by, expected))'

对于第二个问题,您可以使用以下类似方式

private boolean isElementPresent(By by) {
    try {
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}

在断言中使用 is 元素。

【讨论】:

  • 检查元素是否显示不是更好吗???类似的东西 - boolean visible = driver.findElement(By.xpath(locator)).isDisplayed();
  • @Maitreya, boolean visible = driver.findElement(By.xpath(locator)).isDisplayed();也是一种检查元素可用性的方法。
  • @Prashant,在测试用例中使用 Assert 语句是一种好方法吗?或者我们可以在函数中有断言语句。你能告诉我哪个是最佳实践吗?
【解决方案2】:

在你的 catch 块中添加 Assert.fail();

例子:

try {
    ----- your code -----

} catch(Exception e) {
    Assert.fail();
}

希望这能解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多