Moq Roles.AddUserToRole Test

I am writing unit tests for a project in ASP.NET MVC 1.0 using the Moq and MvcContrib TestHelper classes. I ran into a problem.

When I come to Roles.AddUserToRole in my AccountController, I get a System.NotSupportedException exception. The Roles class is static, and Moq cannot mock a static class.

What can I do?

+3
source share
4 answers

You can use a template similar to DI (Injection Dependency). In your case, I would pass the RoleProvider to the AccountController, which by default would be the default RoleProvider, and the layout of the object in your tests. Sort of:

public class AccountController
{
    private MembershipProvider _provider;
    private RoleProvider roleProvider;

    public AccountController()
      : this(null, null)
    {
    }

    public AccountController(MembershipProvider provider, RoleProvider roleProvider)
    {
      _provider = provider ?? Membership.Provider;
      this.roleProvider = roleProvider ?? System.Web.Security.Roles.Provider;
    }
}

MVC , , , AccountController . unit test MockRoleProvider ( Moq ):

[Test]
public void AccountControllerTest()
{
    AccountController controller = new AccountController(new MockMembershipProvider(), new MockRoleProvider());
}

: HttpContext, . HttpContext Moq:

public static HttpContextBase GetHttpContext(IPrincipal principal)
{
  var httpContext = new Mock<HttpContextBase>();
  var request = new Mock<HttpRequestBase>();
  var response = new Mock<HttpResponseBase>();
  var session = new Mock<HttpSessionStateBase>();
  var server = new Mock<HttpServerUtilityBase>();
  var user = principal;


  httpContext.Setup(ctx => ctx.Request).Returns(request.Object);
  httpContext.Setup(ctx => ctx.Response).Returns(response.Object);
  httpContext.Setup(ctx => ctx.Session).Returns(session.Object);
  httpContext.Setup(ctx => ctx.Server).Returns(server.Object);
  httpContext.Setup(ctx => ctx.User).Returns(user);

  return httpContext.Object;
}

:

  public class MockPrincipal : IPrincipal
  {
    private IIdentity _identity;
    private readonly string[] _roles;

    public MockPrincipal(IIdentity identity, string[] roles)
    {
      _identity = identity;
      _roles = roles;
    }

    public IIdentity Identity
    {
      get { return _identity; }
      set { this._identity = value; }
    }

    public bool IsInRole(string role)
    {
      if (_roles == null)
        return false;
      return _roles.Contains(role);
    }
  }

A MockIdentity:

public class MockIdentity : IIdentity
  {
    private readonly string _name;

    public MockIdentity(string userName)    {
      _name = userName;
    }

    public override string AuthenticationType
    {
      get { throw new System.NotImplementedException(); }
    }

    public override bool IsAuthenticated
    {
      get { return !String.IsNullOrEmpty(_name); }
    }

    public override string Name
    {
      get { return _name; }
    }
  }

:

MockIdentity identity = new MockIdentity("JohnDoe");
var httpContext = MoqHelpers.GetHttpContext(new MockPrincipal(identity, null));

, , , , .

+7

, ChangePassword() ASP.NET MVC.

        try
        {
            if (MembershipService.ChangePassword(User.Identity.Name, currentPassword, newPassword))
            {
                if (!TempData.ContainsKey("ChangePassword_success"))
                {
                    TempData.Add("ChangePassword_success", true);
                }

                return PartialView("ChangePassword");

            }

, null, . :

mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);

, , , "johndoe". IPrincipal, User .

0

TypeMock Isolator .. ( + 1'd) Razzie.

0

, , , null, :

mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);

:

        //Arrange (Set up a scenario)
        var mockMembershipService = new Mock<IMembershipService>();
        MockIdentity identity = new MockIdentity("JohnDoe");
        var httpContext = MoqHelpers.GetHttpContext(new MockPrincipal(identity, null));
        var controller = new AccountController(null, mockMembershipService.Object, null, null, null);
        string currentPassword = "qwerty";
        string newPassword = "123456";
        string confirmPassword = "123456";

        // Expectations

         mockMembershipService.Setup(pw => pw.MinPasswordLength).Returns(6);
         mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);

cp.ChangePassword ? MVCContrib Testhelpers Http ..? , User.Identity.Name MVCContrib. - (mock) :

        var builder = new TestControllerBuilder();
        var controller = new AccountController(mockFormsAuthentication.Object, mockMembershipService.Object, mockUserRepository.Object, null, mockBandRepository.Object);
        builder.InitializeController(controller);

EDIT: I came a little further:

        MockIdentity identity = new MockIdentity("JohnDoe");
        var httpContext = MoqHelpers.GetHttpContext(new MockPrincipal(identity, null));
        var controller = new AccountController(null, mockMembershipService.Object, null, null, null);
        controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);

but now I can not get my cp.ChangePassword pending to return true:

mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);

I am sending the string "johndoe" because it requires a string as a parameter to the User.Identity.Name parameter, but it does not return true.

0
source

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


All Articles