背景
- 我正在通过 C# 自动化 PowerPoint 2007
- 我正在使用 Visual Studio 的内置单元测试 (Microsoft.VisualStudio.TestTools.UnitTesting) 为我的代码编写单元测试
- 我在 Office 2007 应用程序自动化方面经验丰富
我的问题
- 当我运行单元测试时,第一个单元测试方法运行良好,之后所有方法都出现有关分离 RCW 的错误
- 我正在创建一个静态 PowerPoint 实例以供测试方法共享,但在第一个测试方法运行后,应用程序 RCW 似乎正在分离
源代码
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestDemo
{
[TestClass]
public class UnitTest1
{
private static Microsoft.Office.Interop.PowerPoint.ApplicationClass
g_app = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
[TestMethod]
public void Test01()
{
g_app.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
}
[TestMethod]
public void Test02()
{
g_app.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
}
}
}
错误消息
Test method TestDemo.UnitTest1.Test02 threw exception:
System.Runtime.InteropServices.InvalidComObjectException: COM
object that has been separated from its underlying RCW cannot be used..
此消息出现在使用 PowerPoint 实例的行上(当我设置 Visible 属性时)
我尝试过的
- 单元测试的顺序不会改变行为
- Word 2007、Visio 2007 等也会出现同样的问题。
- 当使用 NUNIT 编写测试用例时,我没有遇到这些问题 - 显然 Visual Studio 运行单元测试的方式有所不同(并不是暗示 VS 不正确,只是指出它与 NUNIT 不同)
- 它与 Visible 属性无关 - 任何方法或属性的使用都会导致此问题
- 我尝试使用属性 AssemblyInitialize 和 ClassInitialize 来创建实例,但没有任何效果
- Google 搜索和 Binged - 没有明确的答案对我有帮助
评论
- 我可以切换到 NUNIT,但更愿意继续使用 Visual Studio 的 native 单元测试框架
我的问题
- 如何成功创建将在所有测试方法之间共享的 PowerPoint 2007 单个实例
- 如果您能深入了解为什么会发生这种情况,我将不胜感激。
已解决(感谢 ALCONJA)
- 我按照他的建议修改了 .testrunconfig 并且它起作用了。
链接
最佳答案
看起来问题是 MS 单元测试在多个线程中运行,而 NUnit 测试在同一线程中运行。因此,在 MS 测试中运行时对 PowerPoint 的静态引用是 being shared between threads ,COM 不喜欢它,因为默认情况下它是 STA(单线程)。您可以通过添加以下内容将 MS 测试切换为使用 MTA(COM 多线程):
<ExecutionThread apartmentState="MTA" />
到您的 *.testrunconfig 文件(以 XML 格式打开该文件并删除上面的行 anywhere in main the TestRunConfiguration
node )。
不确定 PowerPoint(以及您的特定测试)将如何处理被视为多线程,但您上面的简单示例在 MTA 打开时通过。如果您确实遇到线程问题,您可以尝试创建 unit tests ordered 并查看是否可以解决问题。
关于visual-studio - VS2008 UnitTesting - 与 Office 应用程序对象(PowerPoint 等)分离的 RCW,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1117812/