jag
jag

Reputation: 387

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

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 WebSecurity.CurrentUserId inside the controller.

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.

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

I then found this Mocking WebSecurity provider

I created a wrapper interface & class for websecurity, and mocked the wrapper & 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 (public int CurrentUserId{ get { return 1; }}

Obviously I'm doing something wrong, just not sure what. I've posted code for the unit test, the controller and the 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); }
}

Upvotes: 4

Views: 1862

Answers (1)

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35679

The reason that you're getting 0 back when you hard code 1 is because of this line:

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

The version of the IWebSecurityWrapper you're getting is a mock (since you injected it as such). Adding

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

Should get you what you need. Since we're now telling the mock to return 1 when asked for the CurrentUserId

The reason HttpContextFactory didn't work is because the HttpContextFactory implementations I've seen deal with properties on the controller and I suspect your dependency on HttpContext was inside the WebSecurity class itself, hence why you need the wrapper.

Upvotes: 2

Related Questions