Curious bug of the day

time to read 2 min | 296 words

If you throw an exception on the finalizer thread, expect bad things to happen.

I just run into this issue where both TestDriven.Net and ReSharper Test Runner doesn't handle this issue. I would get a nasty error message from Windows telling me that this is a rouge application and none of my tests will continue to run.

The issue was that several of the tests were creating chain of objects, and the lower most object was a Component, which mean that it is disposable and finalizable. In the dispose method it called a dipose method on a mock object, but because the mock object was no longer in a valid state when the finalizer was called, an exception was thrown.

The fun part is that when I try to fix this, I find out that any exception from the test will cause the mock object to be invalid state and then the finalizer will kick in and dispose the object, which will call the mock, which will throw...

The really nice part is that running the test one by one will not expose this bug. It seems like the finalizer is not getting a chance to run in this case. But the moment you got several tests, it will kick in and kill the tests. It's just two tests, and to fix this I would need to open up a chain of seams in the objects, so for now I'm just calling GC.WaitForPendingFinalizers(). This at least will crash the tests predictably :-)