我带着更多愚蠢的问题回来了
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) 如何断言/验证一个元素不存在?
作为新手,我尝试了很多在 Google 和 Stack Overflow 中找到的东西 - Assert that a WebElement is not present using Selenium WebDriver with java , Selenium WebDriver - Test if element is present , 等。但他们都没有工作。我正在使用 JUnit4,需要一个在元素不存在时应该传递的函数。
谢谢
弥勒佛
P.S:如果这个问题看起来令人困惑或迷失方向,请随时编辑它。
最佳答案
答案 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;
}
}
在断言中使用 is 元素。
关于java - Selenium WebDriver - 两部分 - 1) AssertEquals 失败测试失败 2) 验证元素不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11612541/