简体   繁体   English

使用 Selenium WebDriver 和 java 断言 WebElement 不存在

[英]Assert that a WebElement is not present using Selenium WebDriver with java

In tests that I write, if I want to assert a WebElement is present on the page, I can do a simple:在我编写的测试中,如果我想断言页面上存在 WebElement,我可以做一个简单的事情:

driver.findElement(By.linkText("Test Search"));

This will pass if it exists and it will bomb out if it does not exist.如果它存在,这将通过,如果它不存在,它将被炸毁。 But now I want to assert that a link does not exist.但是现在我想断言链接存在。 I am unclear how to do this since the code above does not return a boolean.我不清楚如何执行此操作,因为上面的代码不会返回 boolean。

EDIT This is how I came up with my own fix, I'm wondering if there's a better way out there still.编辑这就是我想出自己的解决方法的方式,我想知道是否还有更好的方法。

public static void assertLinkNotPresent (WebDriver driver, String text) throws Exception {
List<WebElement> bob = driver.findElements(By.linkText(text));
  if (bob.isEmpty() == false) {
    throw new Exception (text + " (Link is present)");
  }
}

这样做更容易:

driver.findElements(By.linkText("myLinkText")).size() < 1

I think that you can just catch org.openqa.selenium.NoSuchElementException that will be thrown by driver.findElement if there's no such element:我认为你可以捕获org.openqa.selenium.NoSuchElementException如果没有这样的元素,将会由driver.findElement抛出:

import org.openqa.selenium.NoSuchElementException;

....

public static void assertLinkNotPresent(WebDriver driver, String text) {
    try {
        driver.findElement(By.linkText(text));
        fail("Link with text <" + text + "> is present");
    } catch (NoSuchElementException ex) { 
        /* do nothing, link is not present, assert is passed */ 
    }
}

Not Sure which version of selenium you are referring to, however some commands in selenium * can now do this: http://release.seleniumhq.org/selenium-core/0.8.0/reference.html不确定您指的是哪个版本的 selenium,但是 selenium * 中的一些命令现在可以执行此操作: http : //release.seleniumhq.org/selenium-core/0.8.0/reference.html

  • assertNotSomethingSelected assertNotSomethingSelected
  • assertTextNotPresent断言文本不存在

Etc..等等..

There is an Class called ExpectedConditions :有一个名为ExpectedConditions的类:

  By loc = ...
  Boolean notPresent = ExpectedConditions.not(ExpectedConditions.presenceOfElementLocated(loc)).apply(getDriver());
  Assert.assertTrue(notPresent);

Try this -尝试这个 -

private boolean verifyElementAbsent(String locator) throws Exception {
    try {
        driver.findElement(By.xpath(locator));
        System.out.println("Element Present");
        return false;

    } catch (NoSuchElementException e) {
        System.out.println("Element absent");
        return true;
    }
}

使用 Selenium Webdriver 将是这样的:

assertTrue(!isElementPresent(By.linkText("Empresas en Misión")));

It looks like findElements() only returns quickly if it finds at least one element.看起来findElements()只有在找到至少一个元素时才会快速返回。 Otherwise it waits for the implicit wait timeout, before returning zero elements - just like findElement() .否则它在返回零元素之前等待隐式等待超时 - 就像findElement()

To keep the speed of the test good, this example temporarily shortens the implicit wait, while waiting for the element to disappear:为了保持良好的测试速度,这个例子暂时缩短了隐式等待,同时等待元素消失:

static final int TIMEOUT = 10;

public void checkGone(String id) {
    FluentWait<WebDriver> wait = new WebDriverWait(driver, TIMEOUT)
            .ignoring(StaleElementReferenceException.class);

    driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
    try {
        wait.until(ExpectedConditions.numberOfElementsToBe(By.id(id), 0));
    } finally {
        resetTimeout();
    }
}

void resetTimeout() {
    driver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS);
}

Still looking for a way to avoid the timeout completely though...仍在寻找一种方法来完全避免超时...

boolean titleTextfield = driver.findElement(By.id("widget_polarisCommunityInput_113_title")).isDisplayed();
assertFalse(titleTextfield, "Title text field present which is not expected");

You can utlilize Arquillian Graphene framework for this.您可以为此使用Arquillian Graphene框架。 So example for your case could be所以你的情况的例子可能是

Graphene.element(By.linkText(text)).isPresent().apply(driver));

Is also provides you bunch of nice API's for working with Ajax, fluent waits, page objects, fragments and so on.它还为您提供了一堆很好的 API,用于处理 Ajax、流畅的等待、页面对象、片段等。 It definitely eases a Selenium based test development a lot.它无疑大大简化了基于 Selenium 的测试开发。

For node.js I've found the following to be effective way to wait for an element to no longer be present:对于 node.js,我发现以下是等待元素不再存在的有效方法:

// variable to hold loop limit
    var limit = 5;
// variable to hold the loop count
    var tries = 0;
        var retry = driver.findElements(By.xpath(selector));
            while(retry.size > 0 && tries < limit){
                driver.sleep(timeout / 10)
                tries++;
                retry = driver.findElements(By.xpath(selector))
            }

Not an answer to the very question but perhaps an idea for the underlying task:不是对问题的回答,而是对基本任务的想法:

When your site logic should not show a certain element, you could insert an invisible "flag" element that you check for.当您的站点逻辑不应该显示某个元素时,您可以插入一个不可见的“标志”元素来检查。

if condition
    renderElement()
else
    renderElementNotShownFlag() // used by Selenium test

Please find below example using Selenium "until.stalenessOf" and Jasmine assertion.请在下面使用 Selenium "until.stalenessOf" 和 Jasmine 断言查找示例。 It returns true when element is no longer attached to the DOM.当元素不再附加到 DOM 时,它返回 true。

const { Builder, By, Key, until } = require('selenium-webdriver');

it('should not find element', async () => {
   const waitTime = 10000;
   const el = await driver.wait( until.elementLocated(By.css('#my-id')), waitTime);
   const isRemoved = await driver.wait(until.stalenessOf(el), waitTime);

   expect(isRemoved).toBe(true);
});

For ref.: Selenium:Until Doc对于参考: 硒:直到文档

The way that I have found best - and also to show in Allure report as fail - is to try-catch the findelement and in the catch block, set the assertTrue to false, like this:我发现最好的方法 - 并且在 Allure 报告中显示为失败 - 是尝试捕获 findelement 并在 catch 块中,将 assertTrue 设置为 false,如下所示:

    try {
        element = driver.findElement(By.linkText("Test Search"));
    }catch(Exception e) {
        assertTrue(false, "Test Search link was not displayed");
    }

This is the best approach for me这对我来说是最好的方法

public boolean isElementVisible(WebElement element) {
    try { return element.isDisplayed(); } catch (Exception ignored) { return false; }
}

For a JavaScript (with TypeScript support) implementation I came up with something, not very pretty, that works:对于 JavaScript(支持 TypeScript)实现,我想出了一些虽然不是很漂亮但有效的方法:

  async elementNotExistsByCss(cssSelector: string, timeout=100) {
    try {
      // Assume that at this time the element should be on page
      await this.getFieldByCss(cssSelector, timeout);
      // Throw custom error if element s found
      throw new Error("Element found");
    } catch (e) {
      // If element is not found then we silently catch the error
      if (!(e instanceof TimeoutError)) {
        throw e;
      }
      // If other errors appear from Selenium it will be thrown
    }
  }

PS: I am using "selenium-webdriver": "^4.1.1" PS:我正在使用“selenium-webdriver”:“^4.1.1”

findElement will check the html source and will return true even if the element is not displayed. findElement 将检查 html 源,即使该元素未显示也会返回 true。 To check whether an element is displayed or not use -要检查元素是否显示,请使用 -

private boolean verifyElementAbsent(String locator) throws Exception {

        boolean visible = driver.findElement(By.xpath(locator)).isDisplayed();
        boolean result = !visible;
        System.out.println(result);
        return result;
}

For appium 1.6.0 and above适用于 appium 1.6.0 及以上版本

    WebElement button = (new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//XCUIElementTypeButton[@name='your button']"))));
    button.click();

    Assert.assertTrue(!button.isDisplayed());

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

相关问题 使用带有Java的Selenium Webdriver滚动Webelement - Scrolling Webelement using Selenium Webdriver with Java 如何使用带有Java的Selenium WebDriver将鼠标悬停在Web元素上 - How to mouseover on a webelement using Selenium WebDriver with Java 硒WebDriver上的“ isDisplyed”无法检查WebElement是否存在 - Cannot check the WebElement is Present or Not by “isDisplyed” on selenium WebDriver 如何使用Java和Selenium WebDriver识别动态WebElement上传图片 - How to identify dynamic WebElement to upload the picture using Java and Selenium WebDriver 使用带有 Java 的 Selenium WebDriver 在新页面上查找 WebElement - Find a WebElement on the new page using Selenium WebDriver with Java 如何使用Selenium和Java单击WebTable的任何页面上存在的WebElement - How to Click on a WebElement present on any page of WebTable Using Selenium and java 选择列表WebElement的子级-Java-Selenium WebDriver - Select child of List WebElement - Java - Selenium WebDriver Java Selenium Webdriver手动填充列表WebElement - Java Selenium webdriver filling list webelement manually 如何不使用javascriptExecutor在Selenium Webdriver中突出显示Webelement - How to highlight webelement in selenium webdriver not using javascriptExecutor 无法使用Selenium Webdriver通过LinkText查找webElement? - Unable to locate webElement by LinkText using selenium webdriver?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM