NullReferenceException when mocked method has a nullable value type argument, but It.IsAny constraint is not nullable #90

ashmind opened this Issue Feb 7, 2014 · 1 comment


None yet

3 participants



public interface ISomeInterface {
    void DoSomething(Guid? guid);

mock.Setup(x => x.DoSomething(It.IsAny<Guid>()))


System.NullReferenceException : Object reference not set to an instance of an object.
    at Moq.Match`1.Matches(Object value)
    at Moq.MethodCall.Matches(ICallContext call)
    at System.Linq.Enumerable.LastOrDefault(IEnumerable`1 source, Func`2 predicate)
    at Moq.ExtractProxyCall.HandleIntercept(ICallContext invocation, InterceptStrategyContext ctx)
    at Moq.Interceptor.Intercept(ICallContext invocation)
    at Castle.DynamicProxy.AbstractInvocation.Proceed()
    at Castle.Proxies.ISomeInterfaceProxy.DoSomething(Nullable`1 guid)
@benjamin-hodgson benjamin-hodgson pushed a commit to benjamin-hodgson/moq4 that referenced this issue Mar 10, 2015
Benjamin Hodgson Fix NullReferenceException when passing null to a nullable argument b…
…ut trying to match it with a non-nullable IsAny.

This fixes issue #90.

The problem was that Matches() has to cast its input to the type parameter T in order to call the Condition function.
Since T is a reference type, it does not accept nulls and throws a NullReferenceException at the site of the cast.

We get around this by treating value types as a special case. If T is a value type and the input is null, it clearly doesn't match (since value types are not nullable).
@kzu kzu closed this Mar 10, 2015

This seem to back as of latest v. 4.2.1506.2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment