Monday, August 29, 2011

Selenium 2 WebDriver C# Basic Example 2.33.0.0

Learning Selenium 2 with WebDriver in C# can be much harder than it should be. When I started using it in version 2.4.0 I tried a bunch of samples pulled from other peoples blogs and none of the samples worked without having to add/edit code sometimes extensively. I quickly identified a couple reasons for this the code samples didn't work out of the box.
1) First they didn't provide the version of selenium used, this was especially a big problem at the beginning because changes and new features were being added all the time to Selenium 2
2) Second (C# != Java) a lot of the C# samples I found were written Java, also a lot of the C# questions on sites like StackOverflow are written in... Java!

So here is my C# sample that I wrote in C#, good luck.
I started with the Selenium 2.33.0.0 libraries

using OpenQA.Selenium;  
using OpenQA.Selenium.Firefox;  
using NUnit.Framework;  
using System;  
namespace BasicWebDriver  
{  
   [TestFixture]  
   public class BasicGoogleTest  
   {  
     [Test]  
     public void SearchForTest()  
     {  
       string searchText = "Selenium 2 WebDriver C# Basic Example";  
       using (IWebDriver driver = new FirefoxDriver())  
       {  
         driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 10));  
         driver.Navigate().GoToUrl("http://rickcasady.blogspot.com");  
         driver.FindElement(By.Id("b-query")).SendKeys(searchText);  
         driver.FindElement(By.Name("b-query-icon")).Click();   
         Assert.NotNull(driver.FindElement(By.PartialLinkText(searchText)));  
       }  
     }  
   }  
} 
and don't copy this into Eclipse it might not compile.....

No comments: