使用MSTest进行单元测试时,我创建了一个WPF窗口。当此窗口关闭时,Visual Studio将显示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
,其中包含一些文本元素和复选框
答案 0 :(得分:6)
前段时间我偶然发现了这件事。如果我没记错的话,那是因为测试之间的 ,AppDomain的默认Dispatcher没有被正确清理和重新初始化。
为了解决这个问题,我创建了一个DomainNeedsDispatcherCleanup
属性类,负责Dispatcher的正确设置和拆卸。我会在找到它时立即将它包括在内,但请注意我使用的是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
,它应该被修复。