unit-testing - .net core Url.Action mock,怎么做?

标签 unit-testing asp.net-core-mvc moq

如何在测试 Controller Action 期间模拟 Url.Action?

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

感谢您的帮助!

更新
这是我需要测试的 Controller 中的方法。

    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);
    }

我在 mock 这部分时遇到问题:
var callbackUrl = Url.Action("Confirm", "EmailConfirmation", new { userId = user.Id, token }, HttpContext.Request.Scheme);

最佳答案

最后我找到了解决方案!

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

        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 中的 null,我遇到了问题。你需要模拟 HttpContext
_controller.ControllerContext.HttpContext = new DefaultHttpContext();

关于unit-testing - .net core Url.Action mock,怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212066/

相关文章:

visual-studio-2015 - 如何在 MVC 6 应用程序中启用 SSL?

c# - Shaman.EPPlus + ASP.NET Core MVC - 部分已存在异常

c# - 最小起订量工作单位

moq - 尝试使用 Moq 模拟 IObjectSet 时出现 TypeLoadException

entity-framework-4 - 在 Entity Framework 4 中使用 Moq

c# - 单元测试未在 TFS 版本中运行 Release|x64 平台

python - Pandas 单元测试 : How to assert equality of NaT and NaN values?

c# - 编程和单元测试最佳实践

javascript - 在 Angular 单元测试中将表单设置为 $valid

c# - Azure Active Directory 不会使用 ASP.NET Core 2.1 MVC 注销