2013-06-19 16 views
3

当使用MSTest进行单元测试时,我创建了一个WPF窗口。当该窗口关闭时,Visual Studio显示InvalidComObjectException为什么在单元测试中创建的关闭窗口会引发InvalidComObjectException?

COM object that has been separated from its underlying RCW cannot be used. 

它之后的[TestMethod]退出凸起,堆栈仅包含外部码(没有InnerException)。这是我有:

StackTrace: 
     at System.Windows.Input.TextServicesContext.StopTransitoryExtension() 
     at System.Windows.Input.TextServicesContext.Uninitialize(Boolean appDomainShutdown) 
     at System.Windows.Input.TextServicesContext.TextServicesContextShutDownListener.OnShutDown(Object target, Object sender, EventArgs e) 
     at MS.Internal.ShutDownListener.HandleShutDown(Object sender, EventArgs e) 

DeclaringType: 
    {Name = "TextServicesContext" FullName = "System.Windows.Input.TextServicesContext"} 

    Assembly: 
     {PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35} 

这是创建窗口中的代码:

var myWindow = new SomeWindow(errors); 
myWindow.ShowDialog(); 

该窗口包含两个ListView s的一些文本元素,并在其中

回答

6

检查盒我前段时间偶然发现了这个问题。如果我没有记错,这是因为之间的测试您的AppDomain的默认分派器未正确清理并重新初始化。

为了解决这个问题,我创建了一个DomainNeedsDispatcherCleanup属性类,负责分派器的正确设置&拆卸。只要我找到它,我就会把它包含在这里,但请记住,我使用的是XUnit,而不是MSTest。

编辑:刚发现它。这里你去:

using System; 
using System.Reflection; 
using System.Runtime.InteropServices; 
using System.Windows; 
using System.Windows.Interop; 
using System.Windows.Threading; 
using Xunit; 

namespace Boost.Utils.Testing.XUnit.WPF 
{ 
    /// <summary>helful if you stumble upon 'object disconnected from RCW' ComException *after* the test suite finishes, 
    /// or if you are unable to start the test because the VS test runner tells you 'Unable to start more than one local run' 
    /// even if all tests seem to have finished</summary> 
    /// <remarks>only to be used with xUnit STA worker threads</remarks> 
    [AttributeUsage(AttributeTargets.Method)] 
    public class DomainNeedsDispatcherCleanupAttribute : BeforeAfterTestAttribute 
    { 
     public override void After(MethodInfo methodUnderTest) 
     { 
      base.After(methodUnderTest); 

      Dispatcher.CurrentDispatcher.InvokeShutdown(); 
     } 
    } 
} 

哈哈..所以,如你所见,修复是微不足道的。我不记得那个。当然,你只需要在你的拆解中使用InvokeShutdown,它应该是固定的。

+0

太棒了!谢谢!这是MSTest简单的解决方案:'[TestCleanup] public void Cleanup(){Dispatcher.CurrentDispatcher.InvokeShutdown(); }' – Tar

相关问题