简体   繁体   中英

Using Moq to mock a unsafe interface

Is it possible to use Moq to mock an unsafe interface? For example I have (MCVE):

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public unsafe void TestMethod1()
    {
        Mock<IMyUnsafeInterface> mockDependency = new Mock<IMyUnsafeInterface>();
        mockDependency.Setup(i => i.DoWork(It.IsAny<int*>())); // error on this line

        systemUnderTest.Dependency = mockDependency.Object;
        ...
    }
}

public unsafe interface IMyUnsafeInterface
{
    void DoWork(int* intPtr);
    byte* MethodNotRelevantToThisTest1(byte* bytePtr);
    ComplexObject MethodNotRelevantToThisTest2();
    ...
}

However I cannot use an unsafe type as a type parameter and I get the error:

Error   1   The type 'int*' may not be used as a type argument  

Is it possible to setup mocks without using a type parameter to avoid this problem?

(I know the obvious solution is to not use an unsafe interface, I am wondering if there is a solution that does work with unsafe interfaces.)

Edit/Update : it is possible to use a stub class, but I would like to avoid that if it is possible to use Moq as Moq provides considerably less verbose code.

public unsafe class MyUnsafeClass : IMyUnsafeInterface
{
    public void DoWork(int* intPtr) {
        // Do something
    }
    public byte* MethodNotRelevantToThisTest1(byte* bytePtr) {
        throw new NotImplementedException();
    }
    public ComplexObject MethodNotRelevantToThisTest2() {
        throw new NotImplementedException();
    }
    ...
}

Quick answer It's not possible if your type has pointer types in method signatures.


The error you're seeing is because you cannot use a pointer as a type argument. Indeed, in the C# specification you'll find in section 4.4.1 (Type Arguments):

In unsafe code, a type-argument may not be a pointer type.

You can avoid this particular error by changing your code to expect a specific pointer:

Mock<IMyUnsafeInterface> mockDependency = new Mock<IMyUnsafeInterface>();

mockDependency.Setup(i => i.DoWork(any));

// use the mock
mockDependency.Object.DoWork(any);

mockDependency.Verify(p => p.DoWork(any));

However, Moq fails in the Setup call because it's trying to create a Matcher object (used to match setups to invocations) for the argument, which uses the argument's type as a type parameter. This results in the same error as above. Passing your own Match object created via Match.Create or It.Is methods won't work because these methods take a type argument as well.

If you omit the Setup call, taking advantage of the loose mocking behavior, then Moq fails in the Verify call because of the same problem. It's trying to create an object based on the type of the argument parameter so it can match a recorded call with the expression being passed in.

Moq also provides an older method of matching arguments before the It class was provided, where you mark a method with a Matcher attribute:

[Test]
public unsafe void TestMethod1()
{
    int* any = stackalloc int[4];

    Mock<IMyUnsafeInterface> mockDependency = new Mock<IMyUnsafeInterface>();

    // use the mock
    mockDependency.Object.DoWork(any);

    mockDependency.Verify(p => p.DoWork(Is(any)));
}

[Matcher]
public static unsafe int* Is(int* expected) { return null; }
public static unsafe bool Is(int* actual, int* expected)
{
    return actual == expected;
}

This seems like it would work, but it fails with an exception:

System.Security.VerificationException : Operation could destabilize the runtime.
   at lambda_method(Closure)
   at Moq.MatcherFactory.CreateMatcher(Expression expression, Boolean isParams)
   at Moq.MethodCall..ctor(Mock mock, Func`1 condition, Expression originalExpression, MethodInfo method, Expression[] arguments)
   at Moq.Mock.Verify(Mock mock, Expression`1 expression, Times times, String failMessage)
   at Moq.Mock`1.Verify(Expression`1 expression)

I can't quite figure out where this is coming from or how to circumvent it, so that's a dead-end, too.

The best case here would be if you could change int* to IntPtr , which can be mocked normally. If you can't change the type then depending on what you're looking to verify you could make a stub object instead of relying on Moq:

unsafe class StubMyUnsafeInterface : IMyUnsafeInterface
{
    readonly int* expectedIntPtr;

    public StubMyUnsafeInterface(int* expectedIntPtr)
    {
        this.expectedIntPtr = expectedIntPtr;
    }

    public unsafe void DoWork(int* intPtr)
    {
        Assert.That(intPtr == expectedIntPtr);
    }
}

Then in your test:

int* any = stackalloc int[4];
int* other = stackalloc int[4];
var stubMyUnsafeInterface = new StubMyUnsafeInterface(any);

stubMyUnsafeInterface.DoWork(any);   // passes
stubMyUnsafeInterface.DoWork(other); // fails

To avoid this you can try with Wrapper class concept.You can simply wrap your original class or interface.And after that can use your original function inside Wrapper class function.Like below example -

//Wrapper class
public class MyWrapperClass
{
     public YourReturnType MyFunction()
     {
         OriginalClass obj = new OriginalClass();

         //And inside this function call your original function
         return obj.OriginalFunction();
     }

}

The Wrapper class wrap the original type and we can use/mock the original object according to our need.

If you are not aware the concept of Wrapper class then first understands its concept.

http://www.c-sharpcorner.com/Blogs/12038/wrapper-class-in-C-Sharp.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM