Disposing a Moq-Mock

1,032 views
Skip to first unread message

KoenJ

unread,
Jan 30, 2012, 4:35:06 AM1/30/12
to Moq Discussions
I'm writing a unit test, which mocks some interfaces using the Moq
framework.

One of the goals of the test, is to ensure that a certain object does
not have any hard references at some point,
and thus can be garbage collected.

The problem using Moq is, that the mocked classes keep hard references
to objects used by the mock.
A mem profiler shows that Moq.Proxy.ICallContext ..
Castle.Core.Interceptor.IInterceptor[], are holding a hard reference
to the object that should be garbage collected.

Is there any way to dispose a mock, so that i can check that the
object has no more hard references?

Thanks,
Koen

Tim Kellogg

unread,
Feb 7, 2012, 11:40:54 AM2/7/12
to moq...@googlegroups.com
That's a hard question. You could call mock.Object.Dispose() directly, but if that's not good enough you could try using weak a reference (http://msdn.microsoft.com/en-us/library/system.weakreference.aspx). The weak reference won't prevent the object from being garbage collected. However, I'm not sure if the internal interceptor keeps a reference to the object, in which case the whole weak reference idea won't work either. You might have to resort to hand-rolling your mock this time. 

There are some issues with your whole approach. First, even if you can let the garbage collector to reclaim your object, there's no way to guarantee when it will be reclaimed (it happens in another thread). I think you might be wasting your time unit testing the .NET framework instead of just testing your code (this is an anti-pattern). You should be keeping your tests simple. In this case, just call .Dispose() directly and check that it did what it's supposed to. Just have faith that the .NET interpreter will operate as the documentation says.

--Tim



Reply all
Reply to author
Forward
0 new messages