"Invocation failed with mock behavior Strict" exception when mocking a COM object in Moq

2.9k Views Asked by At

I'm trying to implement a unit test with Moq that needs to be able to mock an interface that comes from a COM library. Specifically, I need Moq to recognize that an object of type Point is actually a Point when calling a method that takes type Point as a parameter. This Point type is from an ESRI ArcGIS library. However, even when doing what seems to be a very simple test, I get the invocation failed exception because the call didn't match a setup. Here is the simplest case I can make:

public interface ITest
{
    int TestMethod(Point p);
}

public class TestClass : ITest
{
    public int TestMethod(Point p)
    {
        return 0;
    }
}

[TestMethod]
public void MyTest()
{
    Mock<ITest> mockTest = new Mock<ITest>(MockBehavior.Strict);
    mockTest.Setup(x => x.TestMethod(It.IsAny<Point>())).Returns(0);
    mockTest.Object.TestMethod(new Point());
}

When I call TestMethod, I get the exception. If I look at the type of Point during the run, the type is System.__ComObject, which I can't directly create due to protection level. When I look at the metadata for Point, here's what I see:

using System.Runtime.InteropServices;

namespace ESRI.ArcGIS.Geometry
{
    [CoClass(typeof(PointClass))]
    public interface Point : IPoint
    {
    }
}

I also tried mocking IPoint instead and there was no difference. Is there any way to get Moq to recognize a new Point() in the Setup method? I would even be ok with a way to tell Moq, "Hey, I don't care what any of the passed parameters are. ALWAYS return the specified return NO MATTER WHAT. NEVER return null." But it's starting to look like I'm out of luck here.

0

There are 0 best solutions below