gpt4 book ai didi

c# - 为什么关闭在单元测试中创建的窗口会引发 InvalidComObjectException?

转载 作者:行者123 更新时间:2023-11-30 14:33:04 24 4
gpt4 key购买 nike

当使用 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,其中包含一些文本元素和复选框

最佳答案

我前段时间偶然发现了这个。如果我没记错的话,那是因为在测试之间您的 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 即可修复它。

关于c# - 为什么关闭在单元测试中创建的窗口会引发 InvalidComObjectException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17194361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com