How can I test methods which needs user to be logged

喜欢而已 提交于 2019-12-10 11:45:59

问题


I'm testing some code which needs user to be logged in. When I'm trying to log in with AccountController, it's looks like everything is working, but at AccountController (IPrincipal) User is still null. How can I properly log in (or better, can I mock it somehow)?

public async Task SetupAsync()
        {
            var context = new DataContext();
            var manager = new UserManager(new UserStore(context));
            var accountController = new AccountController(manager);
            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            accountController.AuthenticationManager = mockAuthenticationManager.Object;
            var user = new LoginViewModel
            {
                Email = "user@wp.pl",
                Password = "useruser",
                RememberMe = false
            };
            if (manager.FindByEmail("user@wp.pl") == null)
            {
                await manager.CreateAsync(new User { Email = "user@wp.pl", UserName = "user@wp.pl" }, "useruser");
            }
            await accountController.Login(user, "home/index");
            _calendarController = new CalendarController(context);
        }

Here I got User null exception:

public ClaimsPrincipal CurrentUser
        {
            get { return new ClaimsPrincipal((System.Security.Claims.ClaimsPrincipal)this.User); }
        }

Edit: At return line, I have still User property null. This is sample from AccountController:

var user = await _userManager.FindAsync(model.Email, model.Password);

            if (user != null)
            {
                await SignInAsync(user, model.RememberMe);
                return RedirectToAction("index", "calendar");
            }

回答1:


You should mock your _userManager, and use a mock setup for when the method FindAsync is called. Then you return a fake user you can use later in the code




回答2:


Figured it out on my own, probably not elegant solution but I'm happy anyway. @andreasnico your answer helped, thanks.

I'm mocking my custom ClaimsPrincipal, and setting up UserId - that's what I really needed.

var mockCp = new Mock<IClaimsPrincipal>();
mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
_calendarController.CurrentUser = mockCp.Object;


来源:https://stackoverflow.com/questions/35588659/how-can-i-test-methods-which-needs-user-to-be-logged

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