C# 在NUnit测试中创建WPF窗口后,为什么会出现InvalidComObjectException?
我还没能为努伊特弄明白这一点。有人问了一个类似的问题,在哪里提出了这一例外。答案解决了xUnit的使用问题,询问者报告说他让它为MSTest工作。我尝试调用C# 在NUnit测试中创建WPF窗口后,为什么会出现InvalidComObjectException?,c#,wpf,nunit,C#,Wpf,Nunit,我还没能为努伊特弄明白这一点。有人问了一个类似的问题,在哪里提出了这一例外。答案解决了xUnit的使用问题,询问者报告说他让它为MSTest工作。我尝试调用Dispatcher.CurrentDispatcher.InvokeShutdown()
Dispatcher.CurrentDispatcher.InvokeShutdown()在[TearDown]
、[TestFixtureTearDown]
和[Test]
方法中,我仍然得到异常
public static string Show(string prompt)
{
string input = null;
var t = new Thread(() =>
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
var inputBox = new InputBox(prompt);
inputBox.ShowDialog();
input = inputBox.Input;
}));
Dispatcher.CurrentDispatcher.InvokeShutdown();
}) { IsBackground = true };
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return input;
}
关于我的实现的更多细节:我创建了一个InputBox类,它扩展了System.Windows.Window。我创建了一个静态方法,InputBox.Show(prompt)
,它执行以下代码:
var input = "";
var t = new Thread(() =>
{
var inputBox = new InputBox(prompt);
inputBox.ShowDialog();
input = inputBox.Input;
}) {IsBackground = true};
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return input;
有什么想法吗?您是否尝试过在测试方法之上添加[RequireMTA](使用intelissence证明正确性)属性?ApartmentState.STA-在我看来,这是给您带来麻烦的说法吗?您是否尝试过在测试方法之上添加[RequireMTA](使用intelissence证明正确性)属性?ApartmentState.STA-在我看来,这是一个给您带来麻烦的声明感谢您在有关调度电话的评论中提出的想法。我更改了我的InputBox.Show方法,所以现在看起来像这样,并且工作得很好。我在单元测试中没有任何Dispatcher
调用,也没有得到异常
public static string Show(string prompt)
{
string input = null;
var t = new Thread(() =>
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
var inputBox = new InputBox(prompt);
inputBox.ShowDialog();
input = inputBox.Input;
}));
Dispatcher.CurrentDispatcher.InvokeShutdown();
}) { IsBackground = true };
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return input;
}
感谢您在有关调度电话的评论中提出的想法。我更改了我的InputBox.Show方法,所以现在看起来像这样,并且工作得很好。我在单元测试中没有任何Dispatcher
调用,也没有得到异常
public static string Show(string prompt)
{
string input = null;
var t = new Thread(() =>
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
var inputBox = new InputBox(prompt);
inputBox.ShowDialog();
input = inputBox.Input;
}));
Dispatcher.CurrentDispatcher.InvokeShutdown();
}) { IsBackground = true };
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return input;
}
我在您的代码中没有看到任何调度程序。添加Dispatcher.Run()
作为线程中的最后一行。代码片段没有太大帮助,它实际上没有显示调用InvokeShutdown的过程。WPF对线程非常挑剔。此代码完成后,STA线程是一只死挪威鹦鹉。不要试图阻止它,它正在笼子底部休息,渴望着峡湾。NUnit确实使将测试线程配置为STA线程变得更加困难。在您的代码中,我没有看到任何调度程序。添加Dispatcher.Run()
作为线程中的最后一行。代码片段没有太大帮助,它实际上没有显示调用InvokeShutdown的过程。WPF对线程非常挑剔。此代码完成后,STA线程是一只死挪威鹦鹉。不要试图阻止它,它正在笼子底部休息,渴望着峡湾。NUnit确实使将测试线程配置为STA线程变得更加困难。为了创建一个窗口,线程必须覆盖STA。WPF要求GUI组件使用STA。线程必须是STA才能创建窗口。WPF需要用于GUI组件的STA。在运行进度条(在其自己的窗口中)然后打开第二个窗口时遇到此问题。谢谢。在运行进度条(在自己的窗口中)然后打开第二个窗口时遇到此问题。谢谢