代码之家  ›  专栏  ›  技术社区  ›  namenlos

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

  •  7
  • namenlos  · 技术社区  · 16 年前

    背景

    • 我正在通过C自动生成PowerPoint2007#
    • 我正在使用Visual Studio(Microsoft.VisualStudio.TestTools.UnitTesting)的内置单元测试为代码编写UnitTests。
    • 我在自动化Office2007应用程序方面经验丰富

    我的问题

    • 当我运行单元测试时,第一个单元测试方法运行得很好,所有这一切都是关于分离的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属性时)

    我试过的

    • UnitTests的顺序不会更改行为
    • 同样的问题也出现在Word 2007、Visio 2007等中。
    • 当用nunit编写测试用例时,我不理解这些问题——显然,Visual Studio运行单元测试的方式有所不同(不意味着vs是不正确的,只是指出它与nunit不同)。
    • 它与可见属性无关-任何方法或属性的使用都会导致此问题
    • 我尝试使用属性assemblyinitialize和classinitialize创建实例,但没有任何效果。
    • google&binged-没有明确的答案可以帮助我

    评论

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

    我的问题

    • 如何成功创建一个将在所有测试方法之间共享的PowerPoint2007实例
    • 如果你能洞察 为什么? 发生这种事,我会感激的。

    解决(感谢Alconja)

    • 我按照他的建议修改了.testrunconfig,它运行正常。

    链接

    1 回复  |  直到 12 年前
        1
  •  7
  •   Alconja    16 年前

    看起来问题在于MS单元测试在多个线程中运行,而nunit测试在同一个线程中运行。所以在MS测试中运行时对PowerPoint的静态引用是 being shared between threads ,因为默认情况下它的sta(单线程)是COM不喜欢的。通过添加以下内容,可以将MS测试切换为使用MTA(COM的多线程):

    <ExecutionThread apartmentState="MTA" />
    

    到您的*.testrunconfig文件(以XML格式打开该文件并跳过上面的行 anywhere in main the TestRunConfiguration node )

    不确定PowerPoint(以及您的特定测试)如何处理被视为多线程的问题,但是上面的小例子在打开MTA的情况下通过了。如果确实出现线程问题,可以尝试 unit tests ordered &看看是否解决了问题。