java 使用 selenium Web 驱动程序验证错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47919396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Verify an error message using selenium web driver
提问by Darshani Kaushalya
I want to verify the error message displaying, after login failed. I am always getting "Test Case Failed" from which I have tried.
我想验证登录失败后显示的错误消息。我总是收到我尝试过的“测试用例失败”。
I want to verify the text with "Invalid username or password". below are the codes I tried.
我想用“无效的用户名或密码”来验证文本。下面是我试过的代码。
This is the html code.
这是html代码。
<div id="statusMsg">
<div class="alert in fade alert-error" style="opacity: 1;">
<a class="close" data-dismiss="alert">×</a>
Invalid username or password
</div>
</div>
These is the code I tried.
这些是我试过的代码。
String actualMsg=driver2.findElement(By.xpath("//div[@id='statusMsg']/div")).getText()
String errorMsg= "× Invalid username or password";
if(actualError.equals(errorMsg)) {
System.out.println("Test Case Passed");
}else{
System.out.println("Test Case Failed");
};
The output is always "Test Case Failed".
输出总是“测试用例失败”。
Is There a way to fix this?
有没有办法解决这个问题?
采纳答案by DebanjanB
To extract the text Invalid username or password
you have to reach to the <div>
tag as follows :
要提取文本,Invalid username or password
您必须<div>
按如下方式到达标签:
String actualMsg = driver2.findElement(By.xpath("//div[@id='statusMsg']/div[@class='alert in fade alert-error']")).getAttribute("innerHTML");
Next your expected error message is :
接下来您预期的错误消息是:
String errorMsg = "× Invalid username or password";
As x
is within <a>
tag and Invalid username or password
is within <div>
tag the validation process will need a bit of String
manipulation. To make the validation simpler you can reduce the expected error message as follows :
由于x
在<a>
标签内和Invalid username or password
在<div>
标签内,验证过程需要一些String
操作。为了使验证更简单,您可以减少预期的错误消息,如下所示:
String errorMsg = "Invalid username or password";
Now you can use the following code block to verify if the actualMsg
contains errorMsg
as follows :
现在您可以使用以下代码块来验证是否actualMsg
包含errorMsg
如下:
if(actualMsg.contains(errorMsg))
{
System.out.println("Test Case Passed");
}else
{
System.out.println("Test Case Failed");
};
回答by Indrapal Singh
Inside div you only have text "Invalid username or password", but you are verifying "× Invalid username or password". First print text from String actualMsg and then put correct errorMsg.
在 div 中,您只有文本“用户名或密码无效”,但您正在验证“× 用户名或密码无效”。首先从 String actualMsg 打印文本,然后输入正确的 errorMsg。
String actualMsg = driver2.findElement(By.xpath("//div[@id='statusMsg']/div")).getText()
String errorMsg= "Invalid username or password";
if(actualError.equals(errorMsg)) {
System.out.println("Test Case Passed");
}else{
System.out.println("Test Case Failed");
}
;
;