How to use the Mock setting for nullable types

I have an interface that has parameters with a null value, such as

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

This is how I tried to mock 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, trying to use the method

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

Whenever this line is executed, although this exception is thrown

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

I tried several different combinations, for example, using a setting with a zero parameter, but this also does not work. I am using Moq 4.0.10827, which is the latest version (currently).

Edit: Constructor for notesClient accepts an interface for dataNoticesClient

 public Client(Data.Notices.INotices noticesClient) 

and initialized as follows

 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); 
+4
source share
1 answer

I would debug this test and check the following:

 Data.Notices.ListingOrder.DateDesc 

One of the first three values ​​may be null, so NullReferenceException

By the way, such a chain can signal a design flaw, see the Law of Demeter

0
source

Source: https://habr.com/ru/post/1432934/


All Articles