.NET Core 单元测试如何模拟 HttpContext RemoteIpAddress?

Pix*_*aul 4 c# unit-testing asp.net-identity asp.net-core

我有一个使用 Identity 的 .NET Core 3.1 项目。对于Login页面处理程序,我添加了一行代码,在用户登录后,它会根据用户的 IP 地址更新用户位置:

_locationRepository.UpdateUserLocationAsync(HttpContext.Connection.RemoteIpAddress);
Run Code Online (Sandbox Code Playgroud)

完整代码

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, set lockoutOnFailure: true
        var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
        if (result.Succeeded)
        {
            _locationRepo.UpdateUserLocation(HttpContext.Connection.RemoteIpAddress);
            _logger.LogInformation("User logged in.");
            return LocalRedirect(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

    // If we got this far, something failed, redisplay form
    return Page();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是在编写单元测试时,我不知道如何正确模拟HttpContext. 无论我尝试过什么,我都不断收到空引用异常。

var httpContext = new Mock<HttpContext>();
httpContext.Setup(x => x.Connection.RemoteIpAddress).Returns(new IPAddress(16885952));
Run Code Online (Sandbox Code Playgroud)

我如何嘲笑RemoteIpAddress

小智 5

Xunit + FakeItEasy

            var mockHttpContextAccessor = new Fake<IHttpContextAccessor>();
            var httpContext = new DefaultHttpContext()
            {
                Connection =
                {
                    RemoteIpAddress = new IPAddress(16885952)
                }
            };
            mockHttpContextAccessor.CallsTo(x => x.HttpContext)
                .Returns(httpContext);
            var extractedIpAddress = IpExtractor.GetIpAddress(httpContext);
            //assert 192.168.1.1
Run Code Online (Sandbox Code Playgroud)