0

我目前正在控制器上运行单元测试,该控制器利用 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();
}
4

0 回答 0