简体   繁体   English

如何使用一个驱动程序实例运行c#多个硒单元测试?

[英]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. 我在使用一个驱动程序实例运行多个C#硒单元测试时遇到问题。

Please find my class as below. 请在下面找到我的课程。

Folder : Com.Main.Web.Selenium 文件夹:Com.Main.Web.Selenium

SeleniumTestInitialize.cs is the main class which contains the driver. 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);
    }
}

Folder com.main.tests 文件夹com.main.tests

Test01.cs 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 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)? 您可以看一下该线程,在这里我回答了它的工作方式: 如何在同一浏览器实例中运行多个测试方法而不关闭它(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. 进行此更改后,我的浏览器将仅打开一次TestFixture(如果您使用“使用Microsoft.VisualStudio.TestTools.UnitTesting;”,则打开TestClass),并且该固定装置中的所有[Test]-都将在同一浏览器实例中运行。 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; HI如果您正在使用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. 如果必须在一个浏览器实例中运行两个测试用例,请不要关闭TearDown内部的驱动程序。 AND INITIALIZE THE DRIVER UNDER TextFixtureSetup 并在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: 我使用了NUnit Framework:

using NUnit.Framework;

I then set up my WebDriver initialisation, test and teardown like this: 然后,我像这样设置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();
    }
}

When I Run All tests, the WebDriver driverIE is initialised. 当我运行所有测试时,将初始化WebDriver driverIE。 All tests then execute in that WebDriver instance before the WebDriver instance is closed at the end of the test run. 然后,在测试运行结束之前关闭WebDriver实例之前,所有测试都将在该WebDriver实例中执行。

The tests execute in alphabetical order by default; 默认情况下,测试按字母顺序执行; each test can also execute in isolation. 每个测试也可以独立执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Selenium Web驱动程序C#测试具有多个用户名(存在于excel中)的登录页面? - How to test login page with multiple usernames(present in excel) using selenium web driver c#? Visual Studio C#单元测试 - 使用各种/多个测试初始化​​运行单元测试,多次运行相同的单元测试? - Visual Studio C# unit testing - Run Unit test with varied/multiple test initializations, Run same unit test multiple times? 我如何按顺序依次运行Selenium C#测试用例? - How i can run selenium C# test cases in order one by one? 如何将外部javascript文件嵌入到ac#硒测试单元中? - how to embed an external javascript file to a c# selenium test unit? 如何同时在多个浏览器上运行测试? 硒网格,C#,Specflow,NUnit - How do I run a test on multiple browsers at the same time? Selenium Grid, C#, Specflow, NUnit 如何在 C# 中使用 Selenium 在多个线程上并行运行相同的测试? - How can I run the same test on multiple threads in parallel using Selenium in C#? 如何在不关闭它的情况下在同一个浏览器实例中运行多个测试方法(C#,SeleniumWebDriverz NUnit)? - How to run multiple test methods in same browser instance without closing it (C#, SeleniumWebDriverz NUnit)? 在c#中运行单元测试时如何处理InvalidoperationException - How to handle Invalidoperationexception when run the unit test in c# 如何在单元测试 C# 中的多个线程中重复运行 TestMethod - How to run TestMethod repeatedly in several Threads in Unit Test C# 如何在 C# 中对 Task.run() 进行单元测试? - How to unit test Task.run() in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM