VS2008 UnitTesting - 带有Office应用程序对象的分离RCW(PowerPoint等)

nam*_*los 7 unit-testing mstest ms-office rcw visual-studio

背景

  • 我通过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;
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

错误信息

Test method TestDemo.UnitTest1.Test02 threw exception:
System.Runtime.InteropServices.InvalidComObjectException: COM 
object that has been separated from its underlying RCW cannot be used..
Run Code Online (Sandbox Code Playgroud)

此消息出现在使用PowerPoint实例的行上(当我设置Visible属性时)

我做了什么

  • 单元测试的顺序不会改变行为
  • Word 2007,Visio 2007等出现同样的问题.
  • 在用NUNIT编写测试用例时,我没有遇到这些问题 - 显然,有关visual studio如何运行单元测试(不是暗示VS不正确,只是指出它与NUNIT不同)的不同之处
  • 它与Visible属性无关 - 任何方法或属性的使用都将导致此问题
  • 我已经尝试使用AssemblyInitialize和ClassInitialize属性来创建实例,但没有任何工作
  • 谷歌搜索和Binged - 没有明确的答案可以帮助我

评论

  • 我可以切换到NUNIT,但更愿意继续使用Visual Studio的本机单元测试框架

我的问题

  • 如何成功创建将在所有TestMethods之间共享的PowerPoint 2007的单个实例
  • 如果您能够深入了解为什么会这样,我将不胜感激.

已解决(感谢ALCONJA)

  • 我按照他的建议修改.testrunco​​nfig并且它工作正常.

链接

Alc*_*nja 7

看起来问题是MS单元测试在多个线程中运行,而NUnit测试在同一个线程中运行.因此,在MS测试中运行时对PowerPoint的静态引用是在线程之间共享的,COM不喜欢它,因为默认情况下它是STA(单线程).您可以通过添加以下命令来切换MS测试以使用MTA(COM的多线程):

<ExecutionThread apartmentState="MTA" />
Run Code Online (Sandbox Code Playgroud)

到您的*.testrunco​​nfig文件(以XML格式打开文件并将上面的行放在主TestRunConfiguration节点的任何地方).

不确定PowerPoint(和您的特定测试)将如何处理被视为多线程,但上面的简单示例通过MTA打开.如果确实发生了线程问题,您可以尝试订购单元测试,看看是否能解决问题.