Unit test - httpcontext is null, websecurity.CurrentUserId is not populated either

I have an MVC 4 application for which I am building unit tests. In my GameController, I have an Action, JoinGame, which requires the current user ID. I get this with WebSecurity.CurrentUserId inside the controller.

When I run the unit test for JoinGame, the UserId is not populated. Obviously, during the unit test of the user, there is no "current" user. I'm trying to figure out how to taunt.

The first error I received was System.ArgumentNullException: Value cannot be null. Parameter name; httpContext System.ArgumentNullException: Value cannot be null. Parameter name; httpContext

Then I found this Mocking WebSecurity provider.

I created a shell interface and class for websecurity and made fun of the wrapper and injected websecuritywrapper into the gamecontroller. This allowed httpContext (although at present I really don’t understand why it worked, and there was no HttpContextFactory), however, the CurrentUserId returned by websecuritywrapper is always 0. Even if I rigidly bind it to 1 insider, the websecuritywrapper class ( public int CurrentUserId{ get { return 1; }}

Obviously, I'm doing something wrong, I just don't know what. I have posted the code for unit test, controller and wrapper below.

 public RedirectToRouteResult JoinGame(int gameid) { //_wr is the websecuritywrapper int UserID = _wr.CurrentUserId; //WebSecurity.CurrentUserId; // get userteam for this user and this game UserTeam ut = _UserTeamRepository.GetUserTeam(userteamid:0, gameid: gameid, userid: UserID); int intUTID = 0; if (ut == null) { // no userteam found, create it OperationStatus opStatus = _UserTeamRepository.CreateUserTeam(UserID, gameid); if (opStatus.Status) intUTID = (int)opStatus.OperationID; } else {intUTID = ut.Id; } if (intUTID > 0) { return RedirectToAction("Index", "ViewPlayers", new { id = intUTID }); } else { return RedirectToAction("Index", "Game"); } } 

 [Test] public void Game_JoinGame_Returns_RedirectToAction() { UserProfile creator = new UserProfile(); UserProfile user = new UserProfile(); Game game = new Game(); ICollection<UserTeam> uteams = null; UserTeam ut = new UserTeam(); ICollection<UserTeam_Player> utp = null; List<Game> games = new List<Game> { new Game { Id = 1, CreatorId = 1, Name = "Game1", Creator = creator, UserTeams=uteams}, }; List<UserTeam> userteams = new List<UserTeam> { new UserTeam {Id=1, UserId = 1, GameId=1, User=user, Game = game, UserTeam_Players=utp} }; Mock<IGameRepository> mockGameRepository = new Mock<IGameRepository>(); Mock<IUserTeamRepository> mockUserTeamRepository = new Mock<IUserTeamRepository>(); Mock<IWebSecurityWrapper> mockWSW = new Mock<IWebSecurityWrapper>(); mockUserTeamRepository.Setup(mr => mr.GetAllUserTeams()).Returns(userteams); mockUserTeamRepository.Setup(mr => mr.GetUserTeam(0,1,1)).Returns(ut); mockUserTeamRepository.Setup(mr => mr.CreateUserTeam(1, 1)); //Arrange GameController Controller = new GameController(mockGameRepository.Object, mockUserTeamRepository.Object, mockWSW.Object); // This didn't work //HttpContextFactory.SetFakeAuthenticatedControllerContext(Controller); //Act RedirectToRouteResult result = Controller.JoinGame(1); Assert.AreEqual("Index", result.RouteValues["action"]); } 

 public class WebSecurityWrapper : IWebSecurityWrapper { public int CurrentUserId{ get { return WebSecurity.CurrentUserId; }} public string CurrentUserName { get { return "admin_user"; } } // WebSecurity.CurrentUserName; public bool HasUserId { get { return WebSecurity.HasUserId; } } public bool Initialized { get { return WebSecurity.Initialized; } } public bool IsAuthenticated { get { return WebSecurity.IsAuthenticated; } } public bool ChangePassword(string userName, string currentPassword, string newPassword){return WebSecurity.ChangePassword(userName, currentPassword, newPassword);} public bool ConfirmAccount(string accountConfirmationToken) { return WebSecurity.ConfirmAccount(accountConfirmationToken); } public bool ConfirmAccount(string userName, string accountConfirmationToken) { return WebSecurity.ConfirmAccount(userName,accountConfirmationToken); } public string CreateAccount(string userName, string password, bool requireConfirmationToken = false) { return WebSecurity.CreateAccount(userName, password, requireConfirmationToken = false); } public string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false) { return WebSecurity.CreateUserAndAccount(userName, password, propertyValues = null, requireConfirmationToken = false); } public string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow = 1440) { return WebSecurity.GeneratePasswordResetToken(userName, tokenExpirationInMinutesFromNow = 1440); } public DateTime GetCreateDate(string userName) { return WebSecurity.GetCreateDate(userName); } public DateTime GetLastPasswordFailureDate(string userName){ return WebSecurity.GetLastPasswordFailureDate(userName); } public DateTime GetPasswordChangedDate(string userName) { return WebSecurity.GetPasswordChangedDate(userName); } public int GetPasswordFailuresSinceLastSuccess(string userName) { return WebSecurity.GetPasswordFailuresSinceLastSuccess(userName);} public int GetUserId(string userName){ return WebSecurity.GetUserId(userName);} public int GetUserIdFromPasswordResetToken(string token) { return WebSecurity.GetUserIdFromPasswordResetToken(token); } public void InitializeDatabaseConnection(string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables) { WebSecurity.InitializeDatabaseConnection(connectionStringName, userTableName, userIdColumn, userNameColumn, autoCreateTables); } public void InitializeDatabaseConnection(string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables) { WebSecurity.InitializeDatabaseConnection(connectionString, providerName, userTableName, userIdColumn, userNameColumn, autoCreateTables); } public bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, int intervalInSeconds) { return WebSecurity.IsAccountLockedOut(userName, allowedPasswordAttempts, intervalInSeconds); } public bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, TimeSpan interval) { return WebSecurity.IsAccountLockedOut(userName, allowedPasswordAttempts, interval); } public bool IsConfirmed(string userName){ return WebSecurity.IsConfirmed(userName); } public bool IsCurrentUser(string userName) { return WebSecurity.IsCurrentUser(userName); } public bool Login(string userName, string password, bool persistCookie = false) { return WebSecurity.Login(userName, password, persistCookie = false); } public void Logout() { WebSecurity.Logout(); } public void RequireAuthenticatedUser() { WebSecurity.RequireAuthenticatedUser(); } public void RequireRoles(params string[] roles) { WebSecurity.RequireRoles(roles); } public void RequireUser(int userId) { WebSecurity.RequireUser(userId); } public void RequireUser(string userName) { WebSecurity.RequireUser(userName); } public bool ResetPassword(string passwordResetToken, string newPassword) { return WebSecurity.ResetPassword(passwordResetToken, newPassword); } public bool UserExists(string userName) { return WebSecurity.UserExists(userName); } } 
+4
source share
1 answer

The reason you get 0 when you hard-code 1 because of this line:

 Mock<IWebSecurityWrapper> mockWSW = new Mock<IWebSecurityWrapper>(); 

The version of IWebSecurityWrapper that you get is the layout (since you entered it as such). Adding

 mockSW.Setup(x=>x.CurrentUserId).Returns(1); 

You should get what you need. Since we are now saying that mock returns 1 when asked by CurrentUserId

The reason the HttpContextFactory is not working is because the implementations of the HttpContextFactory I saw concern the properties of the controller, and I suspect your dependency on the HttpContext is inside the WebSecurity class itself, so you need a wrapper.

+2
source

Source: https://habr.com/ru/post/1486115/


All Articles