SeleniumIDEはブラウザ操作を記録してSelenium用のテストケースを作成してくれるFirefoxプラグインです。実際にSeleniumIDEを動かしてC#のテストケースを作成してみましょう。
エクスポート
「ファイル(F)」>「テストケースをエクスポート(E) 」>「C#(WebDriver)」を選択し操作内容をC#で出力します。
次のソースが作成さできます。
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; namespace SeleniumTests { [TestFixture] public class Testcase { private IWebDriver driver; private StringBuilder verificationErrors; private string baseURL; [SetUp] public void SetupTest() { driver = new FirefoxDriver(); baseURL = "http://www.google.co.jp/"; verificationErrors = new StringBuilder(); } [TearDown] public void TeardownTest() { try { driver.Quit(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual("", verificationErrors.ToString()); } [Test] public void TheCaseTest() { driver.Navigate().GoToUrl("/"); driver.FindElement(By.Id("lst-ib")).Clear(); driver.FindElement(By.Id("lst-ib")).SendKeys("Cheese!"); } private bool IsElementPresent(By by) { try { driver.FindElement(by); return true; } catch (NoSuchElementException) { return false; } } } }
テストケースの修正
このままでは操作対象のページに遷移しないため、上手く動きません。以下の行を書き換えます。
//driver.Navigate().GoToUrl("/");
driver.Navigate().GoToUrl(baseUrl);
さらに起動するブラウザをIEに変えて、使っていないメソッドを削除するなどして整形すると以下のソースになります。
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.IE; namespace SeleniumTests { [TestFixture] public class Testcase { private IWebDriver driver; [SetUp] public void SetupTest() { driver = new InternetExplorerDriver(); } [TearDown] public void TeardownTest() { try { driver.Quit(); } catch (Exception) { // Ignore errors if unable to close the browser } } [Test] public void TheCaseTest() { driver.Navigate().GoToUrl("http://www.google.co.jp/"); driver.FindElement(By.Id("lst-ib")).Clear(); driver.FindElement(By.Id("lst-ib")).SendKeys("Cheese!"); } } }