我尝试在C#中搜索IWebDriver的线程安全,并找到使用ThreadLocal的答案。但是当我运行我的测试时,它总是在我的代码中返回比IWebDriver i实例更多的东西,它在运行新测试后发生,我也尝试在IWebDriver.Quit()之后使用ThreadLocal.Dispose()并且我得到异常System.ObjectDisposedException : Cannot access a disposed object. Object name: 'The ThreadLocal object has been disposed.'
。希望有人在C#中使用WebDriver的线程安全工具给我提供建议。
以下是我返回IWebDriver的代码:
public class DriverFactory
{
IWebDriver webDriver;
ThreadLocal<IWebDriver> ThreadDriver;
private DriverFactory ()
{
//Do not instance out side
}
public static DriverFactory instance = new DriverFactory();
public static DriverFactory Instance ()
{
return instance;
}
/// <summary>
/// This method is use for return WebDriver
/// </summary>
public IWebDriver WebDriver
{
get
{
if(ThreadDriver.Value==null)
//if (webDriver == null)
{
throw new NullReferenceException("The driver instance was not initialized. You should first call the method startDriver.");
}
return ThreadDriver.Value;
//return webDriver;
}
private set
{
webDriver = value;
}
}
public void StartDriver (DriverType driverType)
{
switch (driverType)
{
case DriverType.Chrome:
ThreadDriver = new ThreadLocal<IWebDriver>(() =>
{
return new ChromeDriver(Utils.DriverHelper.DriverPath());
},true);
break;
default:
break;
}
}
/// <summary>
/// This method is use for close WebDriver
/// </summary>
public void CloseWebDriver ()
{
//WebDriver.Close();
//WebDriver.Quit();
//WebDriver = null;
//ThreadDriver.Value.Close();
ThreadDriver.Value.Quit();
ThreadDriver.Values.Clear();
}
}
这是我运行测试的代码,我在运行paralell for testParalell1和testParalell2时遇到了问题:
[TestFixture(DriverType.Chrome)]
[TestFixture(DriverType.Chrome)]
[TestFixture(DriverType.Chrome)]
[TestFixture(DriverType.Chrome)]
[Parallelizable(ParallelScope.Self)]
class ChangeDateTime
{
protected DriverType driverType;
public ChangeDateTime (DriverType type)
{
this.driverType = type;
}
[Test]
public void testParalell1 ()
{
DriverFactory.StartDriver(driverType);
IWebDriver driver = DriverFactory.WebDriver;
driver.Url = "http://www.google.com";
Console.WriteLine(driver.Title);
Assert.AreEqual(driver.Title, "Google");
DriverFactory.CloseWebDriver();
}
[Test]
public void testParalell2 ()
{
DriverFactory.StartDriver(driverType);
IWebDriver driver = DriverFactory.WebDriver;
driver.Url = "http://www.google.com";
Console.WriteLine(driver.Title);
Assert.AreEqual(driver.Title, "Google");
DriverFactory.CloseWebDriver();
}
}