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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With