简体   繁体   中英

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);

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

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

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