Xunit为每个新测试创建新的Test类实例(使用WebDriver和C#) [英] Xunit create new instance of Test class for every new Test ( using WebDriver and C#)

查看:209
本文介绍了Xunit为每个新测试创建新的Test类实例(使用WebDriver和C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过Xunit使用Webdriver(Selenium)在同一浏览器中运行多个测试,目前,xunit会为每个新测试启动新的浏览器,下面是示例代码

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

}

推荐答案

虽然我不了解Selenium,但我确实知道xUnit.net为每个测试方法都创建了测试类的新实例,所以这可能解释了为什么您看到的是您要报告的行为:对于每个测试方法,driver字段都被重新初始化,因为构造函数每次都被调用.

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.

为了重用单个FirefoxDriver实例,可以使用xUnit.net的IUseFixture<T>接口:

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

这篇关于Xunit为每个新测试创建新的Test类实例(使用WebDriver和C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆