I use WatiN for some automated tests, and I found that instantiating IE for each test was not scalable. The time to create and shut down each instance of IE eats me alive:
[TestMethod]
public void Verify_Some_Useful_Thing()
{
using (var browser = new IE())
{
browser.GoTo("/someurl");
}
}
However, the using statement turned out to be useful in that I can always guarantee that my IE instance will have its own dispose () method that closes the IE window.
In any case, I created a singleton that supported one instance of IE, which all my tests use in all my test classes:
public class BrowserPool
{
private static readonly Lazy<BrowserPool> _instance = new Lazy<BrowserPool>(() => new BrowserPool());
private IE _browser;
private string _ieHwnd;
private int _threadId;
public IE Browser
{
get
{
var currentThreadId = GetCurrentThreadId();
if (currentThreadId != _threadId)
{
_browser = IE.AttachTo<IE>(Find.By("hwnd", _ieHwnd));
_threadId = currentThreadId;
}
return _browser;
}
set
{
_browser = value;
_ieHwnd = _browser.hWnd.ToString();
_threadId = GetCurrentThreadId();
}
}
private BrowserPool()
{
Browser = new IE();
}
private int GetCurrentThreadId()
{
return Thread.CurrentThread.GetHashCode();
}
public static BrowserPool Instance
{
get
{
return _instance;
}
}
}
And the test now:
[TestMethod]
public void Verify_Some_Useful_Thing()
{
var browser = BrowserPool.Instance.Browser;
browser.GoTo("/someurl");
}
, , IE . , , , IE .
, BrowserPool.Browser () close(), , . BrowserPool, , , , _browser .
, dispose() IE ?