简体   繁体   English

使用selenium Web驱动程序验证错误消息

[英]Verify an error message using selenium web driver

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? 有没有办法来解决这个问题?

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. 由于x<a>标签内且Invalid username or password<div>标签内,验证过程将需要一些String操作。 To make the validation simpler you can reduce the expected error message as follows : 为了使验证更简单,您可以减少预期的错误消息,如下所示:

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

Inside div you only have text "Invalid username or password", but you are verifying "× Invalid username or password". 在div内部,您只有文本“无效的用户名或密码”,但您正在验证“×无效的用户名或密码”。 First print text from String actualMsg and then put correct errorMsg. 首先从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");
    }

; ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM