Danny Birch
Danny Birch

Reputation: 603

How to use Mock setup for nullable types

I have an interface which has nullable parameters like this

Result<Notice> List(int offset, int limit, Guid? publicationId, Guid? profileId, DateTime? toDate, ListingOrder order);

This is how I attempted to mock this this method

mockNoticesClient.Setup(c => c.List(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<Nullable<Guid>>(), It.IsAny<Nullable<Guid>>(), It.IsAny<Nullable<DateTime>>(), Data.Notices.ListingOrder.DateDesc)).Returns(dataNotices);

Then when trying to use the method

var results = this.noticesClient.List(0, 100, null, profileId, latestNoticeTime, Data.Notices.ListingOrder.DateDesc);

Whenever this line is run though this exception is thrown

... threw an exception of type 'System.NullReferenceException' ... {System.NullReferenceException}

I have tried a few different combinations like using setup with null in the parameter but this doesn't work either. I am using Moq 4.0.10827 which is the latest version (at present).

Edit: The constructor for the noticesClient takes the interface for the dataNoticesClient

public Client(Data.Notices.INotices noticesClient)

and initalised like this

mockNoticesClient = new Mock<Data.Notices.INotices>();
noticesClient = new Client(mockNoticesClient.Object);

mockNoticesClient.Setup(c => c.List(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<Nullable<Guid>>(), It.IsAny<Nullable<Guid>>(), It.IsAny<Nullable<DateTime>>(), It.IsAny<Data.Notices.ListingOrder>())).Returns(dataNotices);

mockNoticesClient.Setup(c => c.List(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<Guid?>(), It.IsAny<Guid?>(), It.IsAny<DateTime?>(), It.IsAny<Data.Notices.ListingOrder>())).Returns(dataNotices);

Upvotes: 5

Views: 7162

Answers (2)

Johnny
Johnny

Reputation: 9529

This was the bug within moq library at the time when the question was raised(moq 4.0.10827) but it is solved here. It is possible now to make setup with Nullable<T> and make invocation with null, works perfectly.

public interface INullable
{
    int Method(Guid? guid);
}

var mock = new Mock<INullable>();
mock.Setup(m => m.Method(It.IsAny<Guid?>())).Returns(6);
int a = mock.Object.Method(null); // a is 6

Upvotes: 1

nan
nan

Reputation: 20316

I would debug this test and check the following:

Data.Notices.ListingOrder.DateDesc

One of the first three values might be null, hence NullReferenceException is thrown

BTW, such chaining may signalize a design flaw, see Law of Demeter

Upvotes: 0

Related Questions