I have worked and read various StackOverflow questions and other tutorials and documentation in recent weeks (some of which are given below) to try and find a way to unit test VSTO AddIn.
Unfortunately, this always leads to an exception E_NOINTERFACEin my tests.
The code I use is shown below - one extract of the partial ThisAddin class, overriding RequestComAddinAutomationService, another that describes the interface of the test utility, the test itself, as well as an additional collection confirming that the AddIn assembly and its internal elements are visible for the test.
My question is : why does this not work? I am sure that this follows generally accepted VSTO testing practice.
If this is not possible below, how do I go through VSTO testing? Is .NET remoting / IPC the only solution?
ThisAddin.cs
public partial class ThisAddin
{
#region Testing Utilities
private AddinHelper _comAddinObject;
protected override object RequestComAddInAutomationService()
{
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 (has a link to 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");
var comObject = (IAddinHelper) comAddin.Object;
Assert.AreEqual(true, true);
doc.Close();
}
}
In addition, the project settings are set to "Registration for COM interoperability", and Visual Studio starts without errors - starting it as a non-administrator results in DLLs not being registered; therefore, I also know that COM objects are registered .
Resulting exception
"System.InvalidCastException" MyProject.Tests.dll, : COM- "System.__ ComObject" "MyProject.IAddinHelper". , QueryInterface COM- IID '{59977378-CC79-3B27-9093-82CD7A05CF74}' - : ( HRESULT: 0x80004002 (E_NOINTERFACE)).
StackOverflow
Microsoft
, VSTO .