views:

68

answers:

2

Is there a good way of testing the result of the IDisposable.Dispose()-method?

Thanks for all your answers.

A: 

Ensure that after calling the .Dispose() method that all function and property getters/setters return an ObjectDisposedException.

http://msdn.microsoft.com/en-us/library/system.objectdisposedexception.aspx

NickLarsen
Blech. `ObjectDisposedException` is a horrible code pattern.
Stephen Cleary
Any other ideas then?
MacX
I have honestly never used `IDisposable` to wrap resources which actually need to be released. I have only used it to take advantage of `using` blocks to trigger an event when my the object is done being used. Also, please don't just say something is a horrible code pattern, even if it is, just provide a reason or a link to content on why it is.
NickLarsen
@Stephen Cleary: There are places it's appropriate, but I would suggest that one should examine individual actions to see what makes sense. Trying to read from a disposed socket connection should fail, but trying to invalidate part of a disposed control should simply be a NOP. I wish there were a "TryBeginInvoke" for marshalling updates to a control's thread (if a control gets disposed before it's updated, simply let the update proceed as a NOP).
supercat
The problem with `ObjectDisposedException` is that it introduces an additional state. It bloats the code, as every public-facing property and method must explicitly check the state. This is especially complex in thread-safe types. And it produces *no gain* for all of this added complexity; there is no adequate way to respond to this exception since it indicates a problem in the *code* rather than a *runtime* error. This type of checking is far better done with Contracts. To establish expected behavior is to validate it, when in reality, it is just as useful to state such behavior is undefined.
Stephen Cleary
"If end users can't follow even the most basic software contracts, they won't ever produce working code anyway." - http://www.codeproject.com/KB/dotnet/IDisposable.aspx
Stephen Cleary
No general discussion about IDisposble. Please stick to the topic!
MacX
@MacX: Everything I said was about `ObjectDisposedException`, which is the topic of the answer.
Stephen Cleary
@Stephen Cleary: I think your explanation was great, and absolutely on topic. Also your answer is much better than mine. The only argument I have for returning `ObjectDisposedException` is that I remember it being part of the documented expected behavior. Its been a while though.
NickLarsen
@NickLarsen: You are correct. `ObjectDisposedException` *is* the official recommendation. I just (personally) think that was one of Microsoft's mistakes. :)
Stephen Cleary
+2  A: 

To unit test the Dispose method, invoke Dispose and then check your mocked versions of your connection, session, and cache. Ensure that they are properly closed and cleared.

Stephen Cleary