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);
source share