Dan*_*rch 5 c# testing nullable moq
我有一个具有可空参数的接口
Result<Notice> List(int offset, int limit, Guid? publicationId, Guid? profileId, DateTime? toDate, ListingOrder order);
Run Code Online (Sandbox Code Playgroud)
这就是我尝试模拟此方法的方式
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);
Run Code Online (Sandbox Code Playgroud)
然后在尝试使用该方法时
var results = this.noticesClient.List(0, 100, null, profileId, latestNoticeTime, Data.Notices.ListingOrder.DateDesc);
Run Code Online (Sandbox Code Playgroud)
只要运行此行,尽管会抛出此异常
... threw an exception of type 'System.NullReferenceException' ... {System.NullReferenceException}
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的组合,例如在参数中使用带有null的setup,但这也不起作用。我正在使用的是最新版本的Moq 4.0.10827(当前)。
编辑: noticesClient的构造函数采用dataNoticesClient的接口
public Client(Data.Notices.INotices noticesClient)
Run Code Online (Sandbox Code Playgroud)
像这样诱人
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);
Run Code Online (Sandbox Code Playgroud)
我将调试此测试并检查以下内容:
Data.Notices.ListingOrder.DateDesc
Run Code Online (Sandbox Code Playgroud)
前三个值之一可能为 null,因此NullReferenceException会抛出
顺便说一句,这种链接可能表明设计缺陷,请参阅德米特法则