如何使用Selenium WebDriver

时间:2017-02-01 12:33:36

标签: selenium selenium-webdriver testng

我在Selenium WebDriver脚本中遇到一个问题,在我的逻辑中我想用下面的场景验证表单提交。

1.Submit form with already register details - Details already exists
2.Submit Form with new details - Successfully added.

现在我的问题是短信的定位符如下所示

driver.findElement(By.xpath("//div[@class='alert alert-success']")).getText();
driver.findElement(By.xpath("//div[@class='alert alert-error']")).getText();

现在我需要java中的selenium代码,因为代码会根据屏幕上的文本自动处理文本,以验证我的测试用例是否通过。请提供如何在网页中编写此类情况。

简单我想验证客户是否在系统中注册,如果不是,我应该在基于屏幕消息的系统中注册。

当我同时使用两个xpath时,它会在系统中找到一个文本而另一个不存在则会给出找不到元素的异常,请建议。

3 个答案:

答案 0 :(得分:6)

您可以cssSelector使用或条件。这将检查两个选项并返回找到的第一个选项

driver.findElement(By.cssSelector(".alert.alert-success, .alert.alert-error")).getText();

答案 1 :(得分:1)

如果存在一条消息而其他消息不存在,那么您将获得NoSuchelementException,因为其他消息不存在,这是预期的行为。如果您不希望测试在这种情况下失败,您应该抓住NoSuchelementException。 您甚至可以尝试driver.findElement(By.xpath("//div[contains(@class, 'alert']")).getText();并验证您获得了哪些文字,但我无法确定它是否有效,因为我不知道您的网页的行为和外观。

答案 2 :(得分:1)

您可以将Xpath搜索的结果分配给String变量,然后从那里调整流量。我已经看到,已经为CSS提供了一个答案,但只要您的原始帖子引用Xpath,这里就是Xpath解决方案:

if(isFormAlreadySubmitted.equals("Details already exist"){ System.out.println("Form already submitted!"); } else if(isFormAlreadySubmitted.equals("Successfully added"){ System.out.println("Successfully added a new record!"); } else{ System.out.println("Something went wrong! Couldn't get alert text, is alert present?"); } ;

从这一点开始,您可以使用简单的if语句指示流程:

    Product table
    Id-----Description
 ---------------------------------
    1------It is abcd
    2------It is Efg
    3------It is Xyz
    Product table
    Id------Name------price---date
 -----------------------
    1-------Abcd------10-----1/1/2007
    2-------Efg------20-----2/2/2007