简体   繁体   中英

How to Run c# Multiple Selenium Unit Test with one driver instance?

i have a problem running Multiple C# Selenium Unit Test tests with one driver instance.

Please find my class as below.

Folder : Com.Main.Web.Selenium

SeleniumTestInitialize.cs is the main class which contains the driver.

[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);
    }
}

Folder 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
    }


}

I have created an ordered test and prioritized the tests in the order of execution . But it is invoking two instances of the driver that means two times the browser.

My question is to How to share a single driver object across all selenium unit tests ?? create at the start and close the driver at the end. Thanks.

You can take a look on this thread, where I answered how I did it: How to run multiple test methods in same browser instance without closing it (C#, SeleniumWebDriverz NUnit)?

Basically, I used:

 using Microsoft.VisualStudio.TestTools.UnitTesting;

Instead of:

 using NUnit.Framework;

So now I have next hierarchy:

[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

With this changes, my browser will open only once for TestFixture (or TestClass if you use "using Microsoft.VisualStudio.TestTools.UnitTesting;") and all [Test]-s from that fixture will run in that same browser instance. After all tests are done, browser will close.

Hope this will help someone else in future. Ask me if you need additional help.

HI If you are using using NUnit.Framework;

The code Execution plan is like below. For First Test Case

[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]

If you have to run both test case in one browser instance Dont close the driver inside TearDown. AND INITIALIZE THE DRIVER UNDER 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
        }

I used NUnit Framework:

using NUnit.Framework;

I then set up my WebDriver initialisation, test and teardown like this:

[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();
    }
}

When I Run All tests, the WebDriver driverIE is initialised. All tests then execute in that WebDriver instance before the WebDriver instance is closed at the end of the test run.

The tests execute in alphabetical order by default; each test can also execute in isolation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM