【问题标题】:How to throw error when String is not matched with element字符串与元素不匹配时如何抛出错误
【发布时间】:2019-08-02 07:35:13
【问题描述】:

我正在尝试从链接元素等于字符串的列表元素中单击一个元素。我需要验证如果它们不相等会抛出错误。

当我比较的字符串与使用 if 语句的元素匹配时,它可以工作。一旦我在 else 语句中添加了一个条件,我就会得到一个错误。它以某种方式列出了整个元素

public void clickFromList(By element, String item) throws Exception{
    try {
        List<WebElement> linkElements = driver.findElements(element);
        for (WebElement webElement : linkElements) {
            String eleText = webElement.getText();
            if(eleText.matches(item)) {
                System.out.println("Selected: " + eleText);
                webElement.click();
                System.out.println("Clicked: " + eleText);
                break;
            }else {
                 Assert.assertFalse(true, "Error");
            }
        }
    } catch (NoSuchElementException e) {
          Assert.fail("Can't find the element in the page. The element is: " +element);
    }
}

例外:

java.lang.AssertionError: Error expected [false] but found [true]

【问题讨论】:

  • 如果你想让你的方法抛出错误,抛出异常,不要使用断言。
  • 嗨@Stultuske,我试过了。它使我的 if 语句失败,因为它只捕获了第一个元素。是否需要将元素添加到arraylist?
  • 我不明白你在说什么。一旦您的迭代遇到一个不相等的值,它就会抛出该错误,最好只保留您在迭代期间更新的标志(布尔值),并在迭代完成后检查该值。
  • 嗨,我添加了一个布尔值,它起作用了。谢谢你的帮助。 :)

标签: java selenium cucumber cucumber-java


【解决方案1】:

您可以尝试使用下面给出的代码,如果它适合您,请告诉我。

public void clickFromList(By element, String item) throws Exception{
try {
    List<WebElement> linkElements = driver.findElements(element);
    for (WebElement webElement : linkElements) {
        String eleText = webElement.getText();
        if(eleText.matches(item)) {
            System.out.println("Selected: " + eleText);
            webElement.click();
            System.out.println("Clicked: " + eleText);
            break;
        }
 else 
 {
 //in assert false method string comes first
 Assert.assertFalse("Element not found with the given text in list",false);
        }
    }
} catch (NoSuchElementException e) {
      Assert.fail("Can't find the element in the page. The element is: " +element);
}

}

【讨论】:

  • 您好,感谢您的意见,但我已经尝试过了,但没有成功。 :)
【解决方案2】:

我认为您可以抛出如下自定义异常:

throw new Exception("Message");

【讨论】:

  • 我这样做了,但我的 if 语句失败了,因为 list 只捕获了第一个元素。
  • @Vince 我在上一条评论中解释了这一点。 Aravida,这应该是评论,而不是答案,因为它实际上并没有回答问题
猜你喜欢
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
相关资源
最近更新 更多