¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io

Re: [TDD] How do I unit test a Dispose method ?


 




On 3 February 2014 14:39, Amir Kolsky <amir.kolsky@...> wrote:
?

This only applies to objects that it owns. Otherwise if it dispose of a reference that has been passed to it (say through injection) then it may be closing an object that is still required elsewhere.

?

Which is the problem with IDisposable to begin with. It is well-nigh impossible to define the behavior properly.


I agree that it is difficult. Here is the test list that I used:

  • when the Finalizer is called it releases all unmanaged resources
  • when the Finalizer is called it does NOT Dispose its managed resources (remember that the order of finalization is not guaranteed, so the managed resource may already have been finalized)
  • when?Dispose()?is called all unmanaged resources are released
  • when?Dispose()?is called all managed Disposable objects are Disposed

To conform to the, the target class must also:

  • implement IDisposable
  • provide a?protected virtual Dispose(bool disposing)?method
  • the?Dispose()?method must call?Dispose(true)
  • the?Dispose()?method must suppress finalization
  • if a finalizer is needed, it must call?Dispose(false)
  • handle?Dispose()?being called multiple times
  • throw an ObjectDisposedException in any other public method tries to access disposed objects

Some of these were challenging (or impossible) to write automated tests for, some were just messy.

Join [email protected] to automatically receive all group messages.