Note that there are some explanatory texts on larger screens.

plurals
  1. POUnit test - httpcontext is null, websecurity.CurrentUserId not being populated either
    primarykey
    data
    text
    <p>I have an MVC 4 application that I'm building unit tests for. In my GameController, I have an Action, JoinGame, that requires the current userid. I get this with <code>WebSecurity.CurrentUserId</code> inside the controller.</p> <p>When I run the unit test for JoinGame, UserId is not being populated. Obviously during a unit test there is no 'current' user. I'm trying to figure out how to mock one.</p> <p>The first error I got was was <code>System.ArgumentNullException: Value cannot be null. Parameter name; httpContext</code></p> <ul> <li><p>After much searching, I found <a href="https://stackoverflow.com/questions/11245059/how-to-mock-httpcontext-so-that-it-is-not-null-from-a-unit-test">How to mock httpcontext so that it is not null from a unit test?</a>.</p> <p>I followed the guidance in that link (created a HttpContextFactory, which mocked httpcontext and also set the current controller context to the mocked data). <strong>This didn't have any effect.</strong></p></li> </ul> <p>I then found this <a href="https://stackoverflow.com/questions/15946579/mocking-websecurity-provide">Mocking WebSecurity provider</a></p> <p>I created a wrapper interface &amp; class for websecurity, and mocked the wrapper &amp; injected the websecuritywrapper into the gamecontroller. This solved the httpContext (though I presently don't really understand why this worked and the HttpContextFactory didn't), however the CurrentUserId returned by the websecuritywrapper is always 0. Even if I hardcode it to 1 insider the websecuritywrapper class (<code>public int CurrentUserId{ get { return 1; }}</code></p> <p>Obviously I'm doing something wrong, just not sure what. I've posted code for the unit test, the controller and the wrapper below.</p> <pre><code>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 &gt; 0) { return RedirectToAction("Index", "ViewPlayers", new { id = intUTID }); } else { return RedirectToAction("Index", "Game"); } } </code></pre> <p><b></b></p> <pre><code>[Test] public void Game_JoinGame_Returns_RedirectToAction() { UserProfile creator = new UserProfile(); UserProfile user = new UserProfile(); Game game = new Game(); ICollection&lt;UserTeam&gt; uteams = null; UserTeam ut = new UserTeam(); ICollection&lt;UserTeam_Player&gt; utp = null; List&lt;Game&gt; games = new List&lt;Game&gt; { new Game { Id = 1, CreatorId = 1, Name = "Game1", Creator = creator, UserTeams=uteams}, }; List&lt;UserTeam&gt; userteams = new List&lt;UserTeam&gt; { new UserTeam {Id=1, UserId = 1, GameId=1, User=user, Game = game, UserTeam_Players=utp} }; Mock&lt;IGameRepository&gt; mockGameRepository = new Mock&lt;IGameRepository&gt;(); Mock&lt;IUserTeamRepository&gt; mockUserTeamRepository = new Mock&lt;IUserTeamRepository&gt;(); Mock&lt;IWebSecurityWrapper&gt; mockWSW = new Mock&lt;IWebSecurityWrapper&gt;(); mockUserTeamRepository.Setup(mr =&gt; mr.GetAllUserTeams()).Returns(userteams); mockUserTeamRepository.Setup(mr =&gt; mr.GetUserTeam(0,1,1)).Returns(ut); mockUserTeamRepository.Setup(mr =&gt; 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"]); } </code></pre> <p><b></b></p> <pre><code>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); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload