如何使用一个驱动程序实例运行c#Multiple Selenium Unit Test?

时间:2014-11-14 14:04:31

标签: c# visual-studio unit-testing selenium automated-tests

我在使用一个驱动程序实例运行多个C#Selenium Unit Test测试时遇到问题。

请在下面找到我的课程。

文件夹:Com.Main.Web.Selenium

SeleniumTestInitialize.cs是包含驱动程序的主类。

[DeploymentItem(@"Resources\IEDriverServer.exe")]
public class SeleniumTestInitialize
{
    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }
    private TestContext testContextInstance;

    public bool SeleniumExecutionTerminateFlag=false;

    public SeleniumTestInitialize seleniumTestInitalize;
    public FindWebDriverElement findWebDriverElement;
    public JavaScriptCalls javaScriptCalls;
    public OperateOnWebDriverElement operateOnWebDriverElement;
   **public RemoteWebDriver driver;** 
   // how to use this driver object across multiple unit test classes

    public string baseURL;

    public void SeleniumSetup()
    {
        try
        {
            Console.WriteLine("Starting Driver...........");
            seleniumTestInitalize = new SeleniumTestInitialize();
            var options = new InternetExplorerOptions
            {
                IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                //ForceCreateProcessApi=true
                EnableNativeEvents = false,
                RequireWindowFocus = false,
                IgnoreZoomLevel = true
            };
            driver = new InternetExplorerDriver(TestContext.DeploymentDirectory, options);
            javaScriptCalls = new JavaScriptCalls(driver);
            findWebDriverElement = new FindWebDriverElement(javaScriptCalls);
            operateOnWebDriverElement = new OperateOnWebDriverElement(findWebDriverElement);
            GoToSite(ConfigParameters.WEB_APPLICATION_URL);
            driver.Manage().Window.Maximize();
        }
        catch (Exception e)
        {
            log.Debug("Error Starting Web Driver...........");
            Console.WriteLine(e.StackTrace);
        }

    }

    public bool SeleniumInitalizeCheck()
    {
        if (seleniumTestInitalize != null)
            return true;
        else
            return false;
    }

    public void SeleniumQuit()
    {
        Console.WriteLine("Quitting Driver...........");
        try
        {
            if (driver != null)
            {
                driver.Quit();
            }

            log.Info("Closing Web Driver...........");
            ProcessMgn.killProcessByNames("IEDriverServer");//Make sure the process is killed
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }
    }

    public void GoToSite(string urlToOpen)
    {
        driver.Navigate().GoToUrl(urlToOpen);
    }
}

文件夹com.main.tests

Test01.cs

[TestClass]
public class Test01 : SeleniumTestInitialize
{

    [TestInitialize]
    public void Setup()
    {
        SeleniumExecutionTerminateFlag = false;

        if (!SeleniumInitalizeCheck())
        {
            SeleniumSetup();
        }
    }

    [TestCleanup]
    public void TearDown()
    {
        if (SeleniumExecutionTerminateFlag)
        {
            SeleniumQuit();
        }  
    }

    [TestMethod]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.TestCase", "http://tfsserver:8080/tfs/PoL;project", "1320", DataAccessMethod.Sequential)]
    public void UCP002_M1()
    {
        var userName = this.TestContext.DataRow["UserName"].ToString();
        var passWord = this.TestContext.DataRow["PassWord"].ToString();
        //use the local host adress for your project here->
        baseURL = this.TestContext.DataRow["URL"].ToString();



        driver.Navigate().GoToUrl(baseURL);

        //driver.FindElement(By.XPath("//html/body/div[2]/div/a/p/desc")).Click();
        //driver.FindElement(By.Id("registerLink")).Click();
        driver.FindElement(By.Id("ctl00_LoginTextBox")).Clear();
        driver.FindElement(By.Id("ctl00_LoginTextBox")).SendKeys(userName);
        driver.FindElement(By.Id("ctl00_PasswordTextbox")).Clear();
        driver.FindElement(By.Id("ctl00_PasswordTextbox")).SendKeys(passWord);
        driver.FindElement(By.Id("ctl00_LogInButton")).Click();
    }


}

Test02.cs

[TestClass]
public class Test02 : SeleniumTestInitialize
{

    [TestInitialize]
    public void Setup()
    {
        SeleniumExecutionTerminateFlag = false;

        if (!SeleniumInitalizeCheck())
        {
            SeleniumSetup();
        }
    }

    [TestCleanup]
    public void TearDown()
    {
        if (SeleniumExecutionTerminateFlag)
        {
            SeleniumQuit();
        }  
    }

    [TestMethod]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.TestCase", "http://tfsserver:8080/tfs/PoL;project", "1320", DataAccessMethod.Sequential)]
    public void Test02()
    {
       //some test script
    }


}

我创建了有序测试,并按执行顺序确定了测试的优先级。但它调用两个驱动程序实例,这意味着浏览器的两倍。

我的问题是如何在所有selenium单元测试中共享一个驱动程序对象?在开始时创建并在结束时关闭驱动程序。 感谢。

3 个答案:

答案 0 :(得分:1)

你可以看一下这个帖子,我在那里回答了我的做法:How to run multiple test methods in same browser instance without closing it (C#, SeleniumWebDriverz NUnit)?

基本上,我用过:

 using Microsoft.VisualStudio.TestTools.UnitTesting;

而不是:

 using NUnit.Framework;

所以现在我有下一个层次结构:

[TestFixture]
 [TestFixtureSetup] // this is where I initialize my WebDriver " new FirefoxDriver(); "
  [Test] //first test
  [Test] //second test
  [Test] //third test
[TestFixtureTearDown] // this is where I close my driver

通过这些更改,我的浏览器只会打开一次TestFixture(或TestClass,如果您使用"使用Microsoft.VisualStudio.TestTools.UnitTesting;")并且该夹具中的所有[Test] -s将打开在同一个浏览器实例中运行。完成所有测试后,浏览器将关闭。

希望这将有助于其他人。问我是否需要其他帮助。

答案 1 :(得分:1)

HI如果您使用的是NUnit.Framework;

代码执行计划如下所示。                                首次测试用例

[TestFixtureSetup]   ---->For each test case this will work so here we can          
                          initialize  the driver instance.              
[TestMethod]         ----->test method will goes here
[TearDown]           -----> clean up code
                         **For Second Test Case**
[TestFixtureSetup]               
[TestMethod]
[TearDown]

如果必须在一个浏览器实例中运行两个测试用例 不要关闭TearDown内的驱动程序。 并在TextFixtureSetup下初始化驱动程序

    [TestFixture()]
        public class TestClass
        {

            [TestFixtureSetUp]
            public void Init()
            {
                Driver.initialize(new InternetExplorerDriver());
            }
            [TearDown]
           public void Close()
            {
//dont do any driver.close()
            }
         [TestMethod]
        public void TestCase001()
        {
        //your code goes here
        }
 [TestMethod]
        public void TestCase002()
        {
        //your code goes here
        }

答案 2 :(得分:0)

我使用了NUnit Framework:

using NUnit.Framework;

然后我按照以下方式设置了我的WebDriver初始化,测试和拆解:

[TestFixture()]
class NUnitSeleniumTests
{
    [OneTimeSetUp]
    public void Init()
    {
        driverIE = new InternetExplorerDriver(ConfigurationManager.AppSettings["IEDriver"]);
        driverIE.Manage().Window.Maximize();

        // other setup logic
    }

    [Test]
    public void TestMethod1()
    {
        // Test logic
    }

    [Test]
    public void TestMethod2()
    {
        // Test logic
    }

    ...
    ...
    ...

    [Test]
    public void TestMethodN()
    {
        // Test logic
    }


    [OneTimeTearDown]
    public void  Close()
    {
        driverIE.Close();
    }
}

当我运行所有测试时,WebDriver driverIE被初始化。然后,在测试运行结束时关闭WebDriver实例之前,所有测试都在该WebDriver实例中执行。

默认情况下,测试按字母顺序执行;每个测试也可以单独执行。