0

What's a good way of writing a test to check that the dispose method of the IDisposable interface is properly releasing unmanaged resources after it is called?

   private bool disposed = false;

   protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            // Free any other managed objects here.               
        }

        // Free any unmanaged objects here
        theUnmanagedResource.Dispose();
        disposed = true;
    }

I was thinking I could check if disposed is false after, but it doesn't guarantee that resources are managed.

Another way is setting theUnmanagedResource = null after theUnmanagedResources.Dispose() and check if it is null after in the test cases. But from other posts, they state setting disposed resources to null after is not a good : Setting Objects to Null/Nothing after use in .NET

Community
  • 1
  • 1
roverred
  • 1,841
  • 5
  • 29
  • 46
  • I'm missing where the linked question says it is not good? – Sriram Sakthivel Apr 20 '14 at 07:39
  • You can mock the unmanaged resoure and check whether dispose is called. – Sriram Sakthivel Apr 20 '14 at 07:40
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See [Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). I've edited your title. See [Should questions include “tags” in their titles?](http://meta.stackexchange.com/a/130208/158100) where the consensus is "no, they should not". – rene Apr 20 '14 at 08:50

1 Answers1

0

As described here, you could check if IDispose.Dispose was called directly(object disposed properly), then bool disposing will be true in a virtual void Dispose(bool disposing):

using System;

class BaseClass : IDisposable
{
   // Flag: Has Dispose already been called? 
   bool disposed = false;

   // Public implementation of Dispose pattern callable by consumers. 
   public void Dispose()
   { 
      Dispose(true);
      GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern. 
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) {
         // Free any other managed objects here. 
         //
      }

      // Free any unmanaged objects here. 
      //
      disposed = true;
   }

   ~BaseClass()
   {
      Dispose(false);
   }
}
tas
  • 472
  • 3
  • 6