Xunit create new instance of Test class for every new Test ( using WebDriver and C#)

僤鯓⒐⒋嵵緔 提交于 2019-12-19 06:17:36

问题


Is there any way to run multiple tests in same browser using Webdriver (Selenium) using Xunit, , at present xunit launches new browser for every new test , below is the sample code

public class Class1

{
    private FirefoxDriver driver;
    public Class1()
    {
         driver = new FirefoxDriver();
    }

    [Fact]
    public void Test()
    {
        driver.Navigate().GoToUrl("http://google.com");
        driver.FindElementById("gbqfq").SendKeys("Testing");
    }

    [Fact]
    public void Test2()
    {
        driver.Navigate().GoToUrl("http://google.com");
        driver.FindElementById("gbqfq").SendKeys("Testing again");
    }

}

回答1:


While I don't know Selenium, I do know that xUnit.net creates a new instance of your test class for every test method, so that probably explains why you are seeing the behaviour you're reporting: the driver field is initialized anew for each test method, because the constructor is invoked every time.

In order to reuse a single FirefoxDriver instance, you can use xUnit.net's IUseFixture<T> interface:

public class Class1 : IUseFixture<FirefoxDriver>
{
    private FirefoxDriver driver;

    public void SetFixture(FirefoxDriver data)
    {
        driver = data;
    }

    [Fact]
    public void Test()
    {
        driver.Navigate().GoToUrl("http://google.com");
        driver.FindElementById("gbqfq").SendKeys("Testing");
    }

    [Fact]
    public void Test2()
    {
        driver.Navigate().GoToUrl("http://google.com");
        driver.FindElementById("gbqfq").SendKeys("Testing again");
    }    
}



回答2:


after some investigation able to find the solution here it is and also updated FirefoxDriver to IWebDriver::

   public class SampleFixture : IDisposable
   {
    private IWebDriver driver;
    public SampleFixture()
    {
        driver = new FirefoxDriver();
        Console.WriteLine("SampleFixture constructor called");

    }

    public IWebDriver InitiateDriver()
    {
        return driver;
    }

    public void Dispose()
    {
       // driver.Close();
        driver.Quit();
        Console.WriteLine("Disposing Fixture");
    }
}

public class Class1 : IUseFixture<SampleFixture>
{
    private IWebDriver driver;

    public void SetFixture(SampleFixture data)
    {
        driver = data.InitiateDriver();
    }

    [Fact]
    public void Test()
    {
        driver.Navigate().GoToUrl("http://google.com");
        driver.FindElement(By.Id("gbqfq")).SendKeys("Testing");
    }

    [Fact]
    public void Test2()
    {
        driver.Navigate().GoToUrl("http://google.com");
        driver.FindElement(By.Id("gbqfq")).SendKeys("Testing again");
    }
}


来源:https://stackoverflow.com/questions/22804317/xunit-create-new-instance-of-test-class-for-every-new-test-using-webdriver-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!