Quick answer Impossible if your type has pointer types in method signatures.
The error you see is that you cannot use a pointer as a type argument. Indeed, in the C # specification you will 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));
However, Moq fails to call Setup because it tries to create a Matcher object (used to map settings for invocations) for an argument that uses the argument type as a type parameter. This results in the same error as above. Passing your own Match object created using Match.Create or It.Is methods will not work because these methods also take a type argument.
If you omit the Setup call using the missing mocking behavior, Moq fails in the Verify call due to the same problem. It tries to create an object based on the argument parameter type so that it can match the recorded call with the expression passed.
Moq also provides an older method for matching arguments before the It class was provided, where you mark a method with the Matcher attribute:
[Test] public unsafe void TestMethod1() { int* any = stackalloc int[4]; Mock<IMyUnsafeInterface> mockDependency = new Mock<IMyUnsafeInterface>();
This seems to work, but the failure is ruled out:
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 understand where it comes from or how to get around it, so there’s a dead end too.
The best case here would be if you could change int* to IntPtr , which can be mocked in the usual way. If you cannot change the type, then depending on what you want to test, you can 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);