2012-07-23 42 views
1

我回来了更多的无聊的问题硒的webdriver - 两个部分 - 一)未对失败的assertEquals测试2)确认元素不存在

1)如何,如果是的assertEquals假测试失败?

我有此代码 -

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)如何断言/验证元素不存在?

作为一个新手我试了很多东西,我发现在谷歌和这里的堆栈溢出 - Assert that a WebElement is not present using Selenium WebDriver with javaSelenium WebDriver - Test if element is present等,但没有一次成功。我正在使用JUnit4,并且需要一个在元素不存在时应该通过的函数。

感谢

弥勒

P.S:请随意编辑这个问题,如果它看起来混淆或迷失方向。

+0

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

回答

4

回答1:要使用assert true或false,你应该使用if else来代替,然后通过assert等方式调用函数。

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; 
    } 
} 

+0

检查元素是否显示不好?例如 - boolean visible = driver.findElement(By.xpath(locator))。isDisplayed(); – 2012-10-01 09:30:48

+0

@Maitreya,boolean visible = driver.findElement(By.xpath(locator))。isDisplayed();也是一种检查元素可用性的方法。 – 2012-12-26 17:41:30

+0

@Prashant,在测试用例中使用Assert语句是一种好方法吗?或者我们可以在函数中声明声明。你能告诉我哪个是最好的做法吗? – 2012-12-26 17:42:39

0

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

例子:

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

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

希望这将解决您的问题