stuwilmur
stuwilmur

Reputation: 163

Calling Automocker.Use() with a null parameter

We have a unit test written using Moq.Automocker 3.5.0 which attempts to do the following:

IFoo nullFoo = null;
_automocker.Use<IFoo>(nullFoo)

However, since this change to Moq.Automocker, passing a null to Use is no longer allowed.

Is there another way to deal with a nullable type like this?

Upvotes: 2

Views: 259

Answers (1)

Martin
Martin

Reputation: 31

For anyone else coming to this question, it looks like the developers of Moq have not included the constraint on all signatures of Use(), so changing the example above to:

_automocker.Use(typeof(IFoo), null);

Should enable the test again, for clarity, on upgrading an internal project I hit this issue, the test resembled:

[Fact]
public void ConstructorThrowsExceptionIfGetClientQueryIsNull()
{
    this.autoMocker.Use((IClaimMapper) null);

    Assert.Throws<ArgumentNullException>("getClientQuery",
        () => this.autoMocker.CreateInstance<ClientStore>());
}

This resulted in an exception when running the test:

ConstructorThrowsExceptionIfGetClientQueryIsNull Failed: System.ArgumentNullException: Value cannot be null. (Parameter 'service')
System.ArgumentNullException
Value cannot be null. (Parameter 'service')
   at Moq.AutoMock.AutoMocker.Use[TService](TService service)
   at Xln.IdentityServer.Tests.Stores.ClientStoreTests.ConstructorThrowsExceptionIfGetClientQueryIsNull() in C:\git\xln.identityserver\test\Xln.IdentityServer.Tests\Stores\ClientStoreTests.cs:line 33
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

Changed the test to:

[Fact]
public void ConstructorThrowsExceptionIfGetClientQueryIsNull()
{
    this.autoMocker.Use(typeof(IGetClientByIdAsyncQuery),null);

    Assert.Throws<ArgumentNullException>("getClientQuery",
        () => this.autoMocker.CreateInstance<ClientStore>());
}

No more exception, test passes, sure someone will argue you don't need to do null check constructor injection this way, but having seen the obscure exceptions you get from AutoFac and even .NET, I'll have a null check.

Upvotes: 3

Related Questions