我正在尝试对控制器动作返回正确的视图进行单元测试。我正在使用.NET Core,Moq和NUnit。
我要测试默认的1:1: 345435-345-345-34
2:2: 445345-35-34-345-34
3:3: 3445-34534534-34345
,
构造函数在下面,
ManageController
并尝试对以下public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ILogger<ManageController> logger,
UrlEncoder urlEncoder)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_logger = logger;
_urlEncoder = urlEncoder;
}
动作进行单元测试,并断言成功时它会返回正确的ViewModel。 (并且会添加其他路径,将来会返回不同的ViewModel)
Index
经过多次尝试,我最接近的解决方法如下,
我模拟了[HttpGet]
public async Task<IActionResult> Index()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var model = new IndexViewModel
{
Username = user.UserName,
Email = user.Email,
PhoneNumber = user.PhoneNumber,
IsEmailConfirmed = user.EmailConfirmed,
StatusMessage = StatusMessage
};
return View(model);
}
,并使用ID为“ 1”的UserManager
设置了GetUserASync
方法。我还设置了ClaimsPrincipal
以使用相同的HttpContext
并将其传递给控制器。
由于Action是异步的,因此我不得不使测试方法异步。当前,由于返回的异步ClaimsPrincipal
为空,因此测试失败。我看不到其余测试是否通过,因为我无法越过该错误。
Task
答案 0 :(得分:1)
设置模拟程序以返回任务,以便可以等待它并允许代码按预期方式流动
//...
var appUser = new ApplicationUser {
//...populate as needed
}
mockUserManager
.Setup(_ => _.GetUserAsync(user))
.ReturnsAsync(appUser); // Allows mocked member to be awaited and return desired type
//...