Vla*_*nko 6 unit-testing moq asp.net-core-mvc
如何在测试控制器动作期间模拟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);
}
Run Code Online (Sandbox Code Playgroud)
我有嘲笑这部分的问题:
var callbackUrl = Url.Action("Confirm", "EmailConfirmation", new { userId = user.Id, token }, HttpContext.Request.Scheme);
Run Code Online (Sandbox Code Playgroud)
Vla*_*nko 27
最后我找到了解决方案
当您模拟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;
Run Code Online (Sandbox Code Playgroud)
也!因为HttpContext.Request.Scheme中的null,我有问题.你需要模拟HttpContext
_controller.ControllerContext.HttpContext = new DefaultHttpContext();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2278 次 |
| 最近记录: |