【发布时间】:2017-12-20 15:25:27
【问题描述】:
在过去的几周里,我研究并阅读了各种 StackOverflow 问题以及其他教程和文档(注意下面的一些),试图找到一种对 VSTO 插件进行单元测试的方法。
不幸的是,它总是在我的测试中导致 E_NOINTERFACE 异常。
我使用的代码如下 - ThisAddin 部分类的一个摘录覆盖RequestComAddinAutomationService,另一个描述测试实用程序接口、测试本身,以及一个额外的程序集摘录证明 AddIn 程序集及其内部对测试可见。
我的问题是:为什么这不起作用?我很确定这遵循了公认的 VSTO 测试实践。
如果无法再进行以下操作,应该如何测试 VSTO? .NET 远程处理/IPC 是唯一的解决方案吗?
ThisAddin.cs
public partial class ThisAddin
{
#region Testing Utilities
private AddinHelper _comAddinObject;
protected override object RequestComAddInAutomationService()
{
// This is being called when I debug/run my project, but not when I run the tests
return _comAddinObject ?? (_comAddinObject = new AddinHelper());
}
#endregion
}
#region Testing Utilities
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
Presentation GetPresentation();
string GetString();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper
{
public Presentation GetPresentation()
{
return Globals.ThisAddin... [...];
}
public string GetString()
{
return "Hello World!";
}
}
#endregion
AssemblyInfo.cs
[assembly: InternalsVisibleTo("MyProject.Tests")]
MyUnitTest.cs(引用了MyProject)
[TestClass]
public class BasicTest
{
[TestMethod]
public void TestInstantiates()
{
var application = new Application();
var doc = application.Presentations.Open(@"C:\Presentation.pptx",
MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
var comAddins = application.COMAddIns;
var comAddin = comAddins.Item("MyProject"); // Returns okay
var comObject = (IAddinHelper) comAddin.Object; // Exception occurs
Assert.AreEqual(true, true); // Never reached
doc.Close();
}
}
此外,项目的设置设置为“注册 COM 互操作”,并且 Visual Studio 运行提升而没有错误 - 以非管理员身份运行它会导致 DLL 未注册;因此,我也知道 COM 对象已注册。
产生的异常
MyProject.Tests.dll 中出现“System.InvalidCastException”类型的异常,但未在用户代码中处理 附加信息:无法将“System.__ComObject”类型的 COM 对象转换为接口类型“MyProject.IAddinHelper”。此操作失败,因为 IID 为“{59977378-CC79-3B27-9093-82CD7A05CF74}”的接口的 COM 组件上的 QueryInterface 调用因以下错误而失败:不支持此类接口(HRESULT 异常:0x80004002 (E_NOINTERFACE)) .
堆栈溢出
- How to call VSTO class from other c# project
- Unit Testing VSTO projects
-
VSTO Add-ins, COMAddIns and RequestComAddInAutomationService(
Register for COM Interop不会改变任何东西) - Why cannot I cast my COM object to the interface it implements in C#?(问题可能与 STAThread 无关)
- https://sqa.stackexchange.com/questions/2545/how-do-i-unit-test-word-addin-written-in-c
微软
- https://blogs.msdn.microsoft.com/varsha/2010/08/17/writing-automated-test-cases-for-vsto-application/
- https://msdn.microsoft.com/en-us/library/bb608621.aspx
- 一般工作流背景:https://msdn.microsoft.com/en-us/library/bb386298.aspx
老实说,我不知道如果没有此功能,应该如何测试 VSTO 加载项。
【问题讨论】:
-
这个答案可能会有所帮助:https://stackoverflow.com/a/16943296/2592875
-
感谢您的链接 - 我之前确实遇到过它,不幸的是,STAThread 属性没有产生任何结果。不过,感谢您的参与!
标签: c# testing com vsto office-interop