How to mock ApplicationUserManager from AccountController in MVC5

余生颓废 提交于 2019-12-04 11:33:02

That is probably not exactly what you need, but take a look, maybe you'll get the idea.

AccountController.cs

[HttpGet]
[Route("register")]
[AllowAnonymous]
public ActionResult Register()
{
    if (IsUserAuthenticated)
    {
        return RedirectToAction("Index", "Home");
    }
    return View();
}

public bool IsUserAuthenticated
{
    get 
    { 
        return
        System.Web.HttpContext.Current.User.Identity.IsAuthenticated; 
    }
}

AccountControllerTests.cs

[Test]
public void GET__Register_UserLoggedIn_RedirectsToHomeIndex()
{
    // Arrange
    HttpContext.Current = CreateHttpContext(userLoggedIn: true);
    var userStore = new Mock<IUserStore<ApplicationUser>>();
    var userManager = new Mock<ApplicationUserManager>(userStore.Object);
    var authenticationManager = new Mock<IAuthenticationManager>();
    var signInManager = new Mock<ApplicationSignInManager>(userManager.Object, authenticationManager.Object);

    var accountController = new AccountController(
        userManager.Object, signInManager.Object, authenticationManager.Object);

    // Act
    var result = accountController.Register();

    // Assert
    Assert.That(result, Is.TypeOf<RedirectToRouteResult>());
}

[Test]
public void GET__Register_UserLoggedOut_ReturnsView()
{
    // Arrange
    HttpContext.Current = CreateHttpContext(userLoggedIn: false);
    var userStore = new Mock<IUserStore<ApplicationUser>>();
    var userManager = new Mock<ApplicationUserManager>(userStore.Object);
    var authenticationManager = new Mock<IAuthenticationManager>();
    var signInManager = new Mock<ApplicationSignInManager>(userManager.Object, authenticationManager.Object);

    var accountController = new AccountController(
        userManager.Object, signInManager.Object, authenticationManager.Object);

    // Act
    var result = accountController.Register();

    // Assert
    Assert.That(result, Is.TypeOf<ViewResult>());
}

private static HttpContext CreateHttpContext(bool userLoggedIn)
{
    var httpContext = new HttpContext(
        new HttpRequest(string.Empty, "http://sample.com", string.Empty),
        new HttpResponse(new StringWriter())
    )
    {
        User = userLoggedIn
            ? new GenericPrincipal(new GenericIdentity("userName"), new string[0])
            : new GenericPrincipal(new GenericIdentity(string.Empty), new string[0])
    };

    return httpContext;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!