Unit Test (mvc) -problem with roles

I have an mvc application and I work with poco objects and write unit test. The problem is that my whole test failed when they reached this line of code Roles.IsUserInRole ("someUser", "role"). Should I implement a new interface or repository for roles or ...? thanks

+4
source share
3 answers

I had the same problem when trying to mock Roles.IsUserInRole functions in my coded unit tests. My solution was to create a new class called RoleProvider and an interface with the IsUserInRole method, which was then called 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. Since you have an interface, you can then mock IRoleProvider in your tests, for example, here's how to use Rhino Mocks:

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

Hope this helps.

+10
source

You can configure your own method to test roles that will behave differently in tests, but I prefer tests to set up a context that will work with standard methods.

http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

0
source

You can create a light wrapper using Predicate / Func.

 public static Predicate<string> IsUserInRole = role => Roles.IsUserInRole(role); 

Then use IsUserInRole () instead of Roles.IsUserInRole (). At runtime, you get the same behavior. But during testing, you can override the function so that it does not access RoleProvider

 MyClass.IsUserInRole = role => true; 

If you prefer not to publish static data, you can embed Predicate through your constructor and store it as a private readonly.

 class MyClass { private readonly Predicate<string> IsUserInRole; MyClass(Predicate<string> roleChecker) { this.IsUserInRole = roleChecker } MyClass() : this(role => Roles.IsUserInRole(role)) { } } 

If you use Moq, you can return the layout, and then control the return value and / or check if the method is called. And check what parameter value was sent to Predicate.

 Mock<Predicate<string>> mockRoleChecker = new Mock<Predicate<string>>(); var cut = new MyClass(mockRoleChecker.Object); var expectedRole = "Admin"; mockRoleChecker.SetReturnsDefault<bool>(true); // if not specified will return false which is default(bool) cut.MyMethod(); mockRoleChecker.Verify(x => x(expectedRole), Times.Once()); 
0
source

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


All Articles