有没有办法使用Xunit在使用Webdriver(Selenium)的同一浏览器中运行多个测试,目前xunit为每个新测试启动新的浏览器,下面是示例代码
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");
}
}
driver
字段为每个测试方法重新初始化,因为构造函数每次都被调用。为了重用单个FirefoxDriver
实例,您可以使用xUnit.net的IUseFixture<T>
接口:
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");
}
}
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");
}
}
IUseFixture
不再存在,似乎已被IClassFixture取代。但是我不能直接注入@Mark Seemann发表的FirefoxDriver
:public class DashboardCategoryBoxes : IClassFixture<FirefoxDriver> {
IWebDriver driver;
public DashboardCategoryBoxes(FirefoxDriver driver) {
//this.driver = wrapper.Driver;
this.driver = driver;
}
}
此抛出错误
System.AggregateException : One or more errors occurred. (Class fixture type 'OpenQA.Selenium.Firefox.FirefoxDriver' may only define a single public constructor.) (The following constructor parameters did not have matching fixture data: FirefoxDriver driver) ---- Class fixture type 'OpenQA.Selenium.Firefox.FirefoxDriver' may only define a single public constructor. ---- The following constructor parameters did not have matching fixture data: FirefoxDriver driver
作为一种解决方法,我们可以创建一些没有构造函数的包装器类
public class FirefoxWrapper { FirefoxDriver driver = new FirefoxDriver(); public FirefoxWrapper Driver { get { return driver; } } }
并从那里获取驱动程序
public class DashboardCategoryBoxes : IClassFixture<FirefoxWrapper> { IWebDriver driver; public DashboardCategoryBoxes(FirefoxWrapper wrapper) { driver = wrapper.Driver; } }