.net core Url.Action mock,怎么样?

.net core Url.Action mock, how to?

如何在测试控制器操作期间模拟 Url.Action?

我正在尝试对我的 asp.net 核心控制器操作进行单元测试。 动作逻辑有 Url.Action,我需要模拟它来完成测试,但我找不到正确的解决方案。

感谢您的帮助!

更新 这是我需要测试的控制器中的方法。

    public async Task<IActionResult> Index(EmailConfirmationViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByNameAsync(model.Email);

            if (user == null) return RedirectToAction("UserNotFound");
            if (await _userManager.IsEmailConfirmedAsync(user)) return RedirectToAction("IsAlreadyConfirmed");

            var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.Action("Confirm", "EmailConfirmation", new { userId = user.Id, token }, HttpContext.Request.Scheme);

            await _emailService.SendEmailConfirmationTokenAsync(user, callbackUrl);

            return RedirectToAction("EmailSent");
        }

        return View(model);
    }

我在模拟这部分时遇到问题:

var callbackUrl = Url.Action("Confirm", "EmailConfirmation", new { userId = user.Id, token }, HttpContext.Request.Scheme);

终于找到解决办法了!

当您模拟 UrlHelper 时,您只需要模拟基本方法 Url.Action(UrlActionContext context) 因为所有辅助方法实际上都使用它。

        var mockUrlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
        mockUrlHelper
            .Setup(
                x => x.Action(
                    It.IsAny<UrlActionContext>()
                )
            )
            .Returns("callbackUrl")
            .Verifiable();

        _controller.Url = mockUrlHelper.Object;

还有!由于 HttpContext.Request.Scheme 中的空值,我遇到了问题。你需要模拟 HttpContext

_controller.ControllerContext.HttpContext = new DefaultHttpContext();

我加了

var urlHelperMock = new Mock<IUrlHelper>();
urlHelperMock
  .Setup(x => x.Action(It.IsAny<UrlActionContext>()))
  .Returns((UrlActionContext uac) =>
    $"{uac.Controller}/{uac.Action}#{uac.Fragment}?"
    + string.Join("&", new RouteValueDictionary(uac.Values).Select(p => p.Key + "=" + p.Value)));
controller.Url = urlHelperMock.Object;

到我的通用控制器设置。这有点粗糙,但意味着我可以测试任何生成链接的控制器逻辑。