Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test(mvc) -problem with Roles

I have mvc application and I'm working with poco objects and writing unit test. Problem is that all my test fail when they reach this line of code Roles.IsUserInRole("someUser", "role"). Should I implement new interface or repository for Roles or...? Thx

like image 537
Cipiripi Avatar asked Jan 04 '11 15:01

Cipiripi


1 Answers

I had the same problem when trying to mock the Roles.IsUserInRole functionality in my coded unit tests. My solution was to create a new class called RoleProvider and an interface with method IsUserInRole which then called the System.Web.Security.Roles.IsUserInRole:

public class RoleProvider: IRoleProvider
{
    public bool IsUserInRole(IPrincipal userPrincipal)
    {
        return System.Web.Security.Roles.IsUserInRole(userPrincipal.Identity.Name, "User");
    }
}

Then in my code I call the RoleProvider IsUserInRole method. As you have an interface you can then mock the IRoleProvider in your tests, example shown here is using Rhino Mocks:

var roleProvider = MockRepository.GenerateStub<IRoleProvider>();
roleProvider.Expect(rp => rp.IsUserInRole(userPrincipal)).Return(true);

Hope this helps.

like image 146
JayneT Avatar answered Sep 21 '22 18:09

JayneT