How can I guarantee that I will delete an object in my single cache before closing the application?

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");
            // etc..
            // some assert() statements
        }
     }

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

    /// <summary>
    /// private to prevent direct instantiation.
    /// </summary>
    private BrowserPool()
    {
        Browser = new IE();
    }

    /// <summary>
    /// Get the current executing thread id.
    /// </summary>
    /// <returns>Thread Id.</returns>
    private int GetCurrentThreadId()
    {
        return Thread.CurrentThread.GetHashCode();
    }

    /// <summary>
    /// Accessor for instance
    /// </summary>
    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");
        // some assertions
  }

, , IE . , , , IE .

, BrowserPool.Browser () close(), , . BrowserPool, , , , _browser ​​ .

, dispose() IE ?

+5
1
+4

All Articles