c# - .Net 核心单元测试与 Url.Action
问题描述
我目前正在控制器上运行单元测试,该控制器利用 Url.Action 来获取两条不同路线的绝对路径。我正在使用 Moq 来设置模拟动作。测试当前失败,并显示消息“对象引用未设置为对象的实例”。
[编辑-澄清问题]
当我调试测试时,Url 显示为Mock<IUrlHelper>
带有ActionContext
属性的 a,但在它调用 的行上Url.Action
,该Action
属性显示为 null。在设置不返回为空的Mock<IUrlHelper>
方式时我错过了什么?Url.Action
我检查了多个设置 Mock Url Actions 的选项,但似乎没有什么对我有用。
这是测试的设置
[Fact]
public async void SendGroup_PassesDetailsToNotificationService()
{
UrlActionContext actualContext = null;
var criteria = new NotificationCriteria { Section = 1, Subsection = 2 };
userSvc.GetNotificationGroupReturnValue = new List<NotificationRecipient>
{
new NotificationRecipient{ SmsAuth = true }
};
var actionContext = new ActionContext
{
ActionDescriptor = new ActionDescriptor(),
RouteData = new RouteData(),
};
var urlHelper = new Mock<IUrlHelper>();
urlHelper.SetupGet(h => h.ActionContext).Returns(actionContext);
urlHelper.Setup(h => h.Action(It.IsAny<UrlActionContext>()))
.Callback((UrlActionContext context) => actualContext = context);
controller.Url = urlHelper.Object;
var dummy = await controller.SendGroup(criteria);
Assert.Same(criteria, notificationSvc.SendGroupNotificationDetailUsed);
}
这是控制器的代码
[HttpPost]
public async Task<IActionResult> SendGroup([FromBody]NotificationCriteria criteria)
{
List<NotificationRecipient> recipients = (await userSvc.GetNotificationGroup(
criteria.Section, criteria.Subsection)).ToList();
if (!recipients.Any())
{
return BadRequest();
}
var uro = Url;
var sectionUrl = Url.Action("Index", "ReportHome", new {sectionId = criteria.Section}, Request.Scheme);
var profileUrl = Url.Action("Index", "Profile", null, Request.Scheme);
var detail = new NotificationDetail
{
SectionUrl = sectionUrl,
ProfileUrl = profileUrl,
Recipients = recipients
};
try
{
await notificationSvc.SendGroupNotification(detail);
}
catch
{
return StatusCode(500);
}
return Ok();
}
解决方案
推荐阅读
- html - ngx-pagination - 渲染页面非常慢
- ios - iOS - 在 Localizable.strings 中用粗体字强调
- arm - ARM Cortex A9 - 具有周期精确时钟计数的模拟器
- angular - 如何将加载设置为假输入为空
- r - ddply 使用“group_by”逻辑
- typescript - 如何在 TypeScript 中获取ElementsByclassName?
- php - 更改由数组变量构建的 htmltable 的背景
- javascript - 使用 multiMatch 示例的 appsync 放大过滤器
- javascript - 使用量角器即时更改 Windows 的时区
- node.js - 将文件发布到服务器