Re: How do I unit test a Dispose method ?
David Burstin <[email protected]> Mon, 3 Feb 2014 14:49:02 +1100
| Newsgroups | gmane.comp.programming.test-driven-development |
|---|---|
| Message-ID | <CAKKh91AhYveaLCoQrxsMgK_bOw+bDkhSyuZ9wCWRROFMZZvtcQ@mail.gmail.com> |
On 3 February 2014 14:39, Amir Kolsky <[email protected]> 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 IDisposable design pattern<http://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx>, 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.