Re: How do I unit test a Dispose method ?

David Burstin <[email protected]> Mon, 3 Feb 2014 15:16:13 +1100
Newsgroups gmane.comp.programming.test-driven-development
Message-ID <CAKKh91AT=g5vZc=jcSoaJySLa_mymFutwxxzykQ2wn3Eh6n1rw@mail.gmail.com>
On 3 February 2014 14:48, Amir Kolsky <[email protected]> wrote:

>
>
> Except that B must already be IDisposable. The IDisposable pattern
> requires that any object that owns an IDisposable must itself implement
> IDisposable.
>
>
>
> n  This is inane, as it requires the owning object to know about
> implementation details of it's ownee.
>
I disagree. All that A needs to know is that B implements the IDisposable
interface.



>
>
> I agree completely. My original point was about not injecting B and then
> disposing of it.
>
>                 So how would the original creator of B know when to
> dispose of it? And given that separation of use from construction is
> dogmatic, you will always encounter this problem....
>

The only reason to ever call Dispose() is to initiate an early release of
expensive internal resources. If the original creator of B is finished with
B, then it should call B.Dispose(). If it isn't then it shouldn't. If
unsure, don't call Dispose(),and the garbage collector will eventually
clean up your IDisposables anyway.

Given that this only applies to expensive resources, then ideally the tying
up, use and release of those resources should be as close to each other as
possible. Say B has an Open() and Close() method, and Close() calls
Dispose() internally, B can still be injected and still implement
IDisposable. It's construction and use can still be separated.