我想为帐户控制器的注册操作编写单元测试,在googling之后和Stack over flow我想出来请查看
public void AccountController_Register_NewAccount()
{
// Arrange
var registerViewmodel = new RegisterViewModel
{
Email = "mohtshm@gmail.com",
Password = "P123456a*",
ConfirmPassword = "P123456a*"
};
var appUser = new ApplicationUser
{
Email = "mohtshm@gmail.com",
UserName = "mohtshm@gmail.com"
};
HttpContext.Current = CreateHttpContext(userLoggedIn: true);
var IuserStore = new Mock<IUserStore<ApplicationUser>>();
IdentityResult resultCreateAsync = new IdentityResult(new string[] { });
var userStore = IuserStore.Object;
var userManager = new Mock<ApplicationUserManager>(userStore);
userManager.Setup(u => u.CreateAsync(appUser, registerViewmodel.Password)).ReturnsAsync(resultCreateAsync);
var authenticationManager = new Mock<IAuthenticationManager>();
var signInManager = new Mock<ApplicationSignInManager>(userManager.Object, authenticationManager.Object);
var accountController = new AccountController(
userManager.Object, signInManager.Object);
accountController.AuthenticationManager = authenticationManager.Object;
// Act
var result =
accountController.Register(registerViewmodel).Result;
Assert.IsNotNull(result);
var addedUser = userStore.FindByIdAsync("mohtshm@gmail.com").Result;
Assert.IsNotNull(addedUser);
Assert.AreEqual("mohtshm@gmail.com", addedUser.UserName);
// Assert
//Assert.That(result, Is.TypeOf<RedirectToRouteResult>());
}
让我知道我错过了什么因为注册方法在Nullexception上抛出异常虽然我为IdentityResult对象设置了模拟
自动生成的注册操作代码为:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
对于IAuthenticationManager,我通过this post中提到的属性注入它,我将在后面按照构造函数注入
private IAuthenticationManager _authnManager;
// Modified this from private to public and add the setter
public IAuthenticationManager AuthenticationManager
{
get
{
if (_authnManager == null)
_authnManager = HttpContext.GetOwinContext().Authentication;
return _authnManager;
}
set { _authnManager = value; }
}