WPF unit testing propblem and solution
When testing WPF forms on WinForms hosting WPF controls you'll probably get test run error: One of the background threads threw exception: System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.
Here is a quick sample of code that causes this problem:
class MyDialog
{
public bool Show()
{
System.Windows.Window w = new System.Windows.Window();
w.Show();
}
}
And here's the unit test
using System.Windows.Threading;
[TestClass()]
public class MyDialogTest
{
[TestCleanup]
public void TestCleanup()
{
// Fixing RCW separated problem
Dispatcher.CurrentDispatcher.InvokeShutdown();
}
[TestMethod()]
public void CanShow()
{
MyDialog dialog = new MyDialog();
dialog.Show();
}
}
Try commenting TestCleanup and see what happends...