7

I've recently started converting my automation suites from WatiN to Selenium2. In both cases, I've been using C#.

Although these may seem like simple questions, I've been searching for answers for about 2 weeks with almost no success.

1) Is there a way to assert that an element exists? I've had to resort to creating an abject and expecting an exception to be thrown if it doesn't exist on the page. In WatiN, it was as simple as: assert.isTrue(browser.textField(Find.ById(elementId)).exists);

2) Is there a way to assert that text is present on the page? I've yet to find a work around for this. In WatiN, my test would have been: assert.isTrue(browser.containsText("text"));

Thanks in advance.

4 Answers 4

7

I wouldn't use the WebDriverBackedSelenium class at all. It's designed to be a bridge class to help people migrate there tests using the Selenium RC API (on which very little work is being done) to the Selenium WebDriver API. Rather, I'd use the techniques the WebDriverBackedSelenium class uses in my own tests.

In the case of asserting that an element exists, you had it correct the first time. Catch the NoSuchElementException thrown when you call IWebDriver.FindElement() and an element doesn't exist.

As for testing whether text exists on a page, I'd do the following:

public bool PageContainsText(IWebDriver driver, string textToFind)
{
    return driver.FindElement(By.tagName("body")).Text.Contains(textToFind);
}

Though it might not be entirely obvious from looking at the C# bindings, these are essentially what the WebDriverBackedSelenium methods are doing under the covers.

0
4

Isn't there isElementPresent(String locator) and isTextPresent(String text) function for Selenium object?

1
  • Ah, I didn't realize that I would have to create a WebDriverBackedSelenium implementation in order to use the selenium commands. This seems much simpler now. Thank you very much for the lead on where to look! Commented May 4, 2011 at 14:47
2

In reply to your first question:

If you are using Selenium/Webdriver you can use the WebDriverWait class (see this: link to so answer) or you could use driver.FindElements(..) as it does not throw if no elements are found. You can then use some linq magic to get the first match. So it would look something like this: driver.FindElements(..).FirstOrDefault().

0

Well, I know that there is a function in Selenium called verifyIfTextPresent that you can use. Check this link for more info - assertion/verification docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.