Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock default role provider for controller's action unit test

Hope this is not a dumb question. I've been searching for two days a way to mock calls for system.web.security.roles on my actions.

I want my unit tests to be isolated and not involve calls to external resources such as database where the roles get Stored.

all the answers i found suggested the creation of a custom role provider, but i prefer mocking over the creation of fakes.

the closest i got was with this solution but i didn't found a way for ninject to pass the default role Provider to the constructor when running the project outside the tests.

I know that type Mock provides a more easy solution to this, but I'm using rhino Mocks and is too late to change now.

like image 748
N4n0 Avatar asked Mar 11 '13 03:03

N4n0


1 Answers

I've had same problem like you and after two hours searching I gave it up.

Finally I ended up with creating own mocking role provider - code bellow.

public class MockRoleProvider : RoleProvider
{
    public MockRoleProvider()
        : base()
    {
        Users = new List<User>();
        Roles = new List<Role>();
    }

    #region RoleProvider members
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        if (usernames == null) throw new ArgumentNullException("usernames");
        if (roleNames == null) throw new ArgumentNullException("roleNames");

        foreach (string role in roleNames)
        {
            if (!RoleExists(role)) throw new ProviderException("Role name does not exist.");
        }

        foreach (string user in usernames)
        {
            if (Users.FirstOrDefault(u => u.Username == user) == null) throw new ProviderException("Username does not exist.");
        }

        foreach (string username in usernames)
        {
            User user = Users.FirstOrDefault(u => u.Username == username);
            if (user == null) continue;
            foreach (var rolename in roleNames)
            {
                Role role = Roles.FirstOrDefault(r => r.RoleName == rolename);
                user.Roles.Add(role);
                role.Users.Add(user);
            }
        }
    }

    public override string ApplicationName { get; set; }

    public override void CreateRole(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");
        if (roleName.Contains(",")) throw new ArgumentException("Role names cannot contain commas.");
        if (RoleExists(roleName)) throw new ProviderException("Role name already exists.");

        Roles.Add(new Role { RoleName = roleName });
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        if (role == null) throw new ProviderException("Role name does not exist.");
        if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0) throw new ProviderException("Cannot delete a populated role.");

        Roles.Remove(Roles.FirstOrDefault(r => r.RoleName == roleName));
        return true;
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        return GetUsersInRole(roleName).Where(n => n.Contains(usernameToMatch)).ToArray();
    }

    public override string[] GetAllRoles()
    {
        return Roles.Select(r => r.RoleName).ToArray();
    }

    public override string[] GetRolesForUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        User user = Users.FirstOrDefault(u => u.Username == username);

        if (user == null) return new string[0];

        return user.Roles.Select(r => r.RoleName).ToArray();
    }

    public override string[] GetUsersInRole(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        if (role == null) throw new ProviderException("Role '" + roleName + "' does not exist.");

        return role.Users.Select(u => u.Username).OrderBy(n => n).ToArray();
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        Role role = Roles.FirstOrDefault(r => r.RoleName == roleName);

        return role != null && role.Users.FirstOrDefault(u => u.Username == username) != null;
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        foreach (string roleName in roleNames)
        {
            if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");
            if (!RoleExists(roleName)) throw new ProviderException("Role name not found.");
        }

        foreach (string username in usernames)
        {
            if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

            foreach (string roleName in roleNames)
            {
                if (!IsUserInRole(username, roleName)) throw new ProviderException("User is not in role.");
            }
        }

        foreach (string username in usernames)
        {
            User user = Users.FirstOrDefault(u => u.Username == username);
            if (user == null) continue;
            foreach (string roleName in roleNames)
            {
                Role role = user.Roles.FirstOrDefault(r => r.RoleName == roleName);
                role.Users.Remove(user);
                user.Roles.Remove(role);
            }
        }
    }

    public override bool RoleExists(string roleName)
    {
        if (roleName == null || roleName == "") throw new ProviderException("Role name cannot be empty or null.");

        return Roles.FirstOrDefault(r => r.RoleName == roleName) != null;
    }
    #endregion

    public void ClearAll()
    {
        Users = new List<User>();
        Roles = new List<Role>();
    }

    public void ClearRoles()
    {
        Roles = new List<Role>();
        Users.ForEach(u => u.Roles = new List<Role>());
    }

    public void ClearUsers()
    {
        Users = new List<User>();
        Roles.ForEach(r => r.Users = new List<User>());
    }

    public void CreateUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");
        if (UserExists(username)) throw new ProviderException("User name already exists.");

        Users.Add(new User { Username = username });
    }

    public bool DeleteUser(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        User user = Users.FirstOrDefault(u => u.Username == username);

        if (user == null) throw new ProviderException("User name does not exist.");

        foreach (Role role in user.Roles)
        {
            role.Users.Remove(user);
        }
        Users.Remove(user);
        return true;
    }

    public bool UserExists(string username)
    {
        if (username == null || username == "") throw new ProviderException("User name cannot be empty or null.");

        return Users.FirstOrDefault(u => u.Username == username) != null;
    }

    private List<Role> Roles { get; set; }

    private List<User> Users { get; set; }

    private class Role
    {
        public Role()
        {
            Users = new List<User>();
        }

        public string RoleName { get; set; }
        public List<User> Users { get; set; }
    }

    private class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Username { get; set; }
        public List<Role> Roles { get; set; }
    }
}

It is really basic but full implementation of RoleProvider.

For use MockRoleProvider add to you App.config this lines of XML into <configuration> element:

<system.web>
  <roleManager enabled="true" defaultProvider="MockRoleProvider">
    <providers>
      <add name="MockRoleProvider" type="YourProject.Tests.MockRoleProvider, YourProject.Tests"/>
    </providers>
  </roleManager>
</system.web>

Then in unit test arrange part use this code:

MockRoleProvider mock = Roles.Provider as MockRoleProvider;
if (mock == null) throw new NullReferenceException("MockRoleProvider null exception.");
mock.ClearAll();
mock.CreateUser("SomeUser");
mock.CreateRole("SomeRole");
mock.AddUsersToRoles(new string[] { "SomeUser" }, new string[] { "SomeRole" });
like image 135
Lukáš Kotrba Avatar answered Nov 02 '22 16:11

Lukáš Kotrba