Weird COM Exceptions in SCSF/CAB Unit Tests

The SCSF project was getting a weird error with the unit tests that were brought forward from VS2005 to VS2008.

All the unit tests would pass, however the test run would fail with the following error in a special log file:

One of the background threads threw exception: System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.
at System.Windows.Input.TextServicesContext.StopTransitoryExtension()
at System.Windows.Input.TextServicesContext.Uninitialize(Boolean appDomainShutdown)
at System.Windows.Input.TextServicesContext.OnAppDomainUnloaded(Object sender, EventArgs args)

Of course, we had hundreds of these messages, and no way to correlate them with a specific unit test.

After some work, I was able to find a single repro case.  After some research, it looks like any unit test that creates a Window of any type will do this. The fix is to add a TestCleanup method to your fixture like this one:

// Added a TestCleanup method to deal with the fact that the code was throwing an InvalidComObjectException
// with the information "COM object that has been separated from its underlying RCW cannot be used."
// Fix is based on this bug logged on Connect.Microsoft.Com:
// https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=318333
[TestCleanup]
public void CleanUp()
{
   System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
}

I know that unit tests that create Windows are not ideal, but for things like CAB and SCSF ( code bases I inherited) it may be necessary.

I hope this helps anyone else who runs into this issue.