gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:58:55 24 4
gpt4 key购买 nike

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

_locationRepository.UpdateUserLocationAsync(HttpContext.Connection.RemoteIpAddress);

完整代码
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();
}

我的问题是在编写单元测试时,我不知道如何正确模拟 HttpContext .无论我尝试过什么,我都不断收到空引用异常。
var httpContext = new Mock<HttpContext>();
httpContext.Setup(x => x.Connection.RemoteIpAddress).Returns(new IPAddress(16885952));

我如何模拟 RemoteIpAddress ?

最佳答案

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

关于c# - .NET Core 单元测试如何模拟 HttpContext RemoteIpAddress?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60723816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com