简体   繁体   English

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

[英].net core Url.Action mock, how to?

How to mock Url.Action during testing controller action? 如何在测试控制器动作期间模拟Url.Action?

I'm trying to unit test my asp.net core controller action. 我正在尝试对我的asp.net核心控制器操作进行单元测试。 Logic of action has Url.Action and I need to mock it to complete test but I can't find right solution. 行动逻辑有Url.Action,我需要模仿它来完成测试,但我找不到正确的解决方案。

Thank you for your help! 谢谢您的帮助!

UPDATE this is my method in controller that I need to test. 更新这是我需要测试的控制器中的方法。

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

I have problem with mocking this part: 我有嘲笑这部分的问题:

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

Finally I found solution! 最后我找到了解决方案

When you are mocking UrlHelper you need to mock only base method Url.Action(UrlActionContext context) because all helper methods actually use it. 当您模拟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;

Also! 也! I have problem because of null in HttpContext.Request.Scheme. 因为HttpContext.Request.Scheme中的null,我有问题。 You need to mock HttpContext 你需要模拟HttpContext

_controller.ControllerContext.HttpContext = new DefaultHttpContext();

I added 我补充道

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;

To my generic Controller setup. 到我的通用控制器设置。 Which is a bit roughnready but means I can test any controller logic that generates links. 这有点粗糙,但意味着我可以测试任何生成链接的控制器逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM