利用Selenium搭建Nunit測試框架

Just4life發表於2013-08-28

1)下載並安裝NUnit-2.6.1,下載地址http://download.csdn.net/detail/czh4869623/4582584

2)下載Newtonsoft.Json.dll,Webdriver.dll(.NET4.0),下載地址http://download.csdn.net/detail/czh4869623/4742196

(如果你的環境是.NET3.5請下載selenium-dotnet-2.26.0裡面包含Webdriver.dll(.NET3.5)和Webdriver.dll(.NET4.0)下載地址http://download.csdn.net/detail/czh4869623/4743828

3)下載chromedriver.exe,IEDriverServer.exe,Ionic.Zip.dll,下載地址http://download.csdn.net/detail/czh4869623/4742208

4)開啟VS(我這裡是VS2010)File > New Project > Class Library > Name: SeleniumNUnitTest

5)新增引用:在專案中新增資料夾dll然後將Newtonsoft.Json.dll和Webdriver.dll放入dll資料夾中,並新增引用(在新增Newtonsoft.Json.dll請檢視說明文件),新增nunit.framework引用。

6)將chromedriver.exe,IEDriverServer.exe,Ionic.Zip.dll新增到\bin\Debug下面並將Ionic.Zip.dll新增引用。

7)編寫程式碼如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using WTWebUIAuto;


namespace SeleniumNUnitTest
{
    [TestFixture]
    public class SeleniumNUnitTestClass
    {
        private IWebDriver driver;

        public SeleniumNUnitTestClass() { }
 
        [SetUp]
        public void LoadDriver() 
        { 
            Console.WriteLine("SetUp");
            LoadDriverByBrowser("chrome");
        }
        private void LoadDriverByBrowser(string browserName)
        {
            switch (browserName)
            {
                case "ie"://開啟IE瀏覽器(確保已安裝IE),會呼叫\bin\Debug下的IEDriverServer.exe。
                    driver = new InternetExplorerDriver();
                    break;
                case "chrome"://開啟Chrome瀏覽器(確保已安裝Chrome),會呼叫\bin\Debug下的chromedriver.exe()。
                    driver = new ChromeDriver();
                    break;
                case "firefox"://開啟FireFox瀏覽器(確保已安裝FireFox),會呼叫\bin\Debug下的Ionic.Zip.dll。
                    driver = new FirefoxDriver();
                    break;
                default:
                    driver = new InternetExplorerDriver();
                    break;
            }

    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1000));
            driver.Navigate().GoToUrl("http://www.baidu.com");
        }
 
        [Test]
        public void Search()
        {
            Console.WriteLine("Test");
            string searchString = "hyddd";
            driver.FindElement(By.Id("kw")).SendKeys(searchString);
            driver.FindElement(By.Id("su")).Click();

            Assert.True(driver.Title.Contains("百度搜尋_hyddd"),"search failed.");
        }
        [TearDown]
        public void UnloadDriver() 
        { 
            Console.WriteLine("TearDown"); 
            driver.Quit(); 
        }

    }
}



8)按F6生成成功

9)開啟NUnit(File—Open Project)找到測試專案生成的dll(D:\test\SeleniumNUnitTest\SeleniumNUnitTest\bin\Debug\SeleniumNUnitTest.dll)

相關文章