[英]Selenium WebDriver - two part - 1) Fail test on AssertEquals failure 2)Verify Element not present
I am back with more silly questions 我回来时有更多愚蠢的问题
1) How to fail a test if AssertEquals is false? 1)如果AssertEquals为假,如何使测试失败?
I have this code - 我有这个代码 -
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;
}
This code displays "Width incorrect" when the width does not match the expected value but the test case passes. 当宽度与预期值不匹配但测试用例通过时,此代码显示“宽度不正确”。 I want the test to fail if the width are unequal.
如果宽度不相等,我希望测试失败。
2) How to assert/verify an Element is NOT present? 2)如何断言/验证元素不存在?
As a novice I tried many things I found in Google and here in Stack Overflow - Assert that a WebElement is not present using Selenium WebDriver with java , Selenium WebDriver - Test if element is present , etc. But none of them worked. 作为一个新手,我尝试了很多我在Google和Stack Overflow中发现的东西 - 断言使用Selenium WebDriver和java , Selenium WebDriver 不存在WebElement - 测试元素是否存在等等。但是它们都没有工作。 I am working with JUnit4 and need a function that should pass if the element is not present.
我正在使用JUnit4,如果元素不存在,需要一个应该通过的函数。
Thanks 谢谢
Maitreya 弥勒
PS: Please feel free edit this question if it looks confusing or disoriented. PS:如果看起来令人困惑或迷失方向,请随意编辑这个问题。
Answer 1: To use assert true or false you should use if else instead and then call the function by assert eg 答案1:要使用assert true或false,你应该使用if else代替然后通过assert调用函数eg
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;
}
Then use compareWidthPixels as ' AssertTrue(compareWidthPixels(by, expected))
' in your test 然后在测试中使用compareWidthPixels作为'
AssertTrue(compareWidthPixels(by, expected))
'
Similarly for 2nd question you can use following 同样对于第二个问题,您可以使用以下
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
using is element in assertions. 在断言中使用is元素。
Add Assert.fail();
添加
Assert.fail();
in your catch block. 在你的阻止块。
Example: 例:
try {
----- your code -----
} catch(Exception e) {
Assert.fail();
}
Hope this will solve your problem 希望这能解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.