C# 如何对可空类型使用模拟设置
我有一个接口,它有如下可为空的参数C# 如何对可空类型使用模拟设置,c#,testing,moq,nullable,C#,Testing,Moq,Nullable,我有一个接口,它有如下可为空的参数 Result<Notice> List(int offset, int limit, Guid? publicationId, Guid? profileId, DateTime? toDate, ListingOrder order); 无论何时运行此行,都会引发此异常 ... threw an exception of type 'System.NullReferenceException' ... {System.NullReference
Result<Notice> List(int offset, int limit, Guid? publicationId, Guid? profileId, DateTime? toDate, ListingOrder order);
无论何时运行此行,都会引发此异常
... threw an exception of type 'System.NullReferenceException' ... {System.NullReferenceException}
我尝试了一些不同的组合,比如在参数中使用带有null的setup,但这也不起作用。我使用的是Moq 4.0.10827,这是最新版本(目前)
编辑:
NoticeClient的构造函数接受DataNoticeClient的接口
public Client(Data.Notices.INotices noticesClient)
并且是这样开始的
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);
mocknoticeclient=newmock();
NoticeClient=新客户端(mockNoticeClient.Object);
mocknoticeclient.Setup(c=>c.List(It.IsAny()、It.IsAny()、It.IsAny()、It.IsAny()、It.IsAny()、It.IsAny())。返回(dataNotices);
mocknoticeclient.Setup(c=>c.List(It.IsAny()、It.IsAny()、It.IsAny()、It.IsAny()、It.IsAny()、It.IsAny())。返回(dataNotices);
我将调试此测试并检查以下各项:
Data.Notices.ListingOrder.DateDesc
前三个值之一可能为null,因此会引发NullReferenceException
... threw an exception of type 'System.NullReferenceException' ... {System.NullReferenceException}
顺便说一句,这种链接可能表明存在设计缺陷,请参见这是提出问题时
moq
库中的缺陷(moq 4.0.10827
),但问题已经解决。现在可以使用设置为空
并使用空
进行调用,这两种方法都非常有效
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
公共接口不可用
{
int方法(Guid?Guid);
}
var mock=new mock();
Setup(m=>m.Method(It.IsAny())。返回(6);
int a=mock.Object.Method(null);//a是6
设置了它的值,我也尝试过使用它。IsAny(enum)提供如何使用mocknoticeclient
,在哪里注入它,从哪里获得noticeclient
。什么是dataNotices
?您可以发布nullref异常的完整堆栈跟踪吗?哪个变量为null结果
或通知客户端
?如果noticeClient
,则应检查它是否已被赋值。两个变量均不为null,而是list方法所采用的参数。出于某种原因,每当一个可为null的参数实际输入为null时,Moq就会抛出一个错误。您是否有异常的完整堆栈跟踪?
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