gpt4 book ai didi

c# - 无法让 Mocked 方法返回 null

转载 作者:行者123 更新时间:2023-11-30 21:32:15 25 4
gpt4 key购买 nike

我正在使用 Moq 模拟一个方法,我希望该方法返回 null,但它没有返回 null,我不确定为什么。

这是我的设置代码:

var mock2 = new Mock<ReminderRepository>(stubPatientRemindersDBModelContainer);
mock2.CallBase = true;
mock2.Setup(x => x.GetPatientEscalations(userName, patientId, startDateTime, endDateTime, new DataTable()))
.Returns((PatientEscalationsDto)null);

调试时,我希望分配给 GetPatientEscalations 的变量为 null,但事实并非如此。

我做错了什么?

最佳答案

检查传递到模拟设置中的参数。

 mock2
.Setup(x => x.GetPatientEscalations(userName, patientId, startDateTime, endDateTime, new DataTable()))
.Returns((PatientEscalationsDto)null);

如果它们与调用成员时实际传入的内容不匹配,它将恢复到您拥有的碱基调用 CallBase启用。

尝试使用 It.IsAny<T>() 放松对模拟成员的期望参数匹配器

 mock2
.Setup(x => x.GetPatientEscalations(
It.IsAny<string>(),
It.IsAny<int>(), //this is an assumption. use desired type here
It.IsAny<DateTime>(),
It.IsAny<DateTime>(),
It.IsAny<DataTable>()))
.Returns((PatientEscalationsDto)null);

这样传递的任何参数都将匹配并调用模拟成员以按预期运行。

关于c# - 无法让 Mocked 方法返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52445376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com