Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7870271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T01:34:11+00:00 2026-06-03T01:34:11+00:00

I have successfully setup up mocking to test asp.net forms authorization but I am

  • 0

I have successfully setup up mocking to test asp.net forms authorization but I am seeing some unexpected behavior with the Role membership and the Authorize attribute. Specifically when the ChangePassword method is called as shown below I would expect that I would get a Unauthorized Access redirect to the Logon screen however I am able to step all the way through the ChangePassword method and receive a change password success. Can anyone help direct me in what I am doing wrong?

I have tested that in the ChangePassword method calling the IsUserInRole method does work as expected and I can redirect to the Logon screen in that condition but that seems burdensome to test for that condition in all my methods. Thanks in advance. I have also tried not assigning the user to a role (instead of returning false with mock) but the result is the same, change password succeeds.

    [TestMethod]
    public void TestProfile()
    {
        string testUserName = "userName", password = "password1", newPassword = "newPassword1";
        var prov = new Mock<IMembershipProvider>();
        prov.Setup(v => v.ValidateUser(testUserName, password)).Returns(true);
        var user = new Mock<MembershipUser>();
        var frmAuth = new Mock<IFormsAuthentication>();
        user.Setup(v => v.ChangePassword(password, newPassword)).Returns(true);
        prov.Setup(v => v.GetUser(testUserName, true)).Returns(user.Object);
        AccountController ctrl = new AccountController(prov.Object, frmAuth.Object);
        var ctrlCtx = new Mock<ControllerContext>();
        ctrlCtx.SetupGet(x => x.HttpContext.User.Identity.Name).Returns(testUserName);
        ctrlCtx.SetupGet(x => x.HttpContext.User.Identity.IsAuthenticated).Returns(true);
        //with this line I would expect to see a redirect to unauhorized
        ctrlCtx.Setup(x => x.HttpContext.User.IsInRole("RoleToTest")).Returns(false);
        ctrl.ControllerContext = ctrlCtx.Object;
        ctrl.Url = Moq.Mock.Of<IUrlHelper>(x => x.IsLocalUrl(It.IsAny<string>()) == true);

        ChangePasswordModel changePass = new ChangePasswordModel() { NewPassword = newPassword, OldPassword = password, ConfirmPassword = password };
        var result = ctrl.ChangePassword(changePass) as ViewResult;
        string expectedViewName = "Logon";
        Assert.AreEqual(result.ViewName, expectedViewName, true /* ignoreCase */,
            string.Format("The expected view '{0}' was not returned. Did change password succeed?", expectedViewName));

    }


    [Authorize(Roles="RoleToTest")]
    [HttpPost]
    public ActionResult ChangePassword(ChangePasswordModel model)
    {
        if (ModelState.IsValid)
        {

            // ChangePassword will throw an exception rather
            // than return false in certain failure scenarios.
            bool changePasswordSucceeded;
            try
            {
                MembershipUser currentUser = membershipProvider.GetUser(User.Identity.Name, true /* userIsOnline */);
                changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
            }
            catch (Exception e)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(e);
                changePasswordSucceeded = false;
            }

            if (changePasswordSucceeded)
            {
                return View("ChangePasswordSuccess");
            }
            else
            {
                ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View("ChangePassword", model);
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T01:34:13+00:00Added an answer on June 3, 2026 at 1:34 am

    Specifically when the ChangePassword method is called as shown below I
    would expect that I would get a Unauthorized Access redirect to the
    Logon screen however I am able to step all the way through the
    ChangePassword method and receive a change password success.

    Your expectation is wrong. Attributes such as [Authorize] are just metadata baked into the assembly at compile-time. If there’s nothing to interpret them, well, nothing will happen at all at runtime.

    The thing is that the [Authorize] attribute is used by the ASP.NET MVC request processing pipeline. In your unit test you are doing a simple call of the controller action. Nothing more. There’s no code to maker any sense of this attribute.

    So you don’t need to unit test that your controller action is redirecting to the LogOn page if the user is not authenticated. What you have to unit test is that your controller action is decorated with the Authorize attribute. The fact that this attribute will redirect to the Logon page when placed on a controller action is something that the ASP.NET MVC team already extensively unit tested during the development of the framework so you don’t need to repeat their job. Just trust them.

    So here’s how a typical unit test could look like:

    [TestMethod]
    public void ChangePassword_Action_Should_Be_Accessible_Only_To_Users_Belonging_To_The_RoleToTest_Role()
    {
        Expression<Func<AccountController, ActionResult>> changePwdEx = 
            x => x.ChangePassword(null);
        var authorize = (changePwdEx.Body as MethodCallExpression)
            .Method
            .GetCustomAttributes(typeof(AuthorizeAttribute), true)
            .OfType<AuthorizeAttribute>()
            .First();
    
        Assert.AreEqual("RoleToTest", authorize.Roles);
    }
    

    Alright, now you have unit tested that this controller action is only accessible to users belonging to the RoleToTest role.

    In your next unit test you assume that a user belongs to this role (by mocking the corresponding classes) and you assert that the body of the controller action executes as expected.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have successfully setup routing in Asp.Net 4.0 webforms. I have set up: routeCollection.MapPageRoute(Default
I have a .NET 3.5 Setup Package Project which installs my application successfully. The
I have successfully setup a localhost (Individual Installs) with Apache 2.2, MySQL and PHP,
Have anyone successfully managed to setup a combined Java/C++ project for Eclipse? What I
I have successfully implemented interop beftween Win32 application and managed .Net dll as described
I have successfully setup htaccess to do this: domain.com/ad.php?ad_id=bmw_m3_2498224 INTO: domain.com/ads/bmw_m3_2498224 However, I have
I am trying to setup secure socket communication to a server. I have successfully
I have successfully setup an HTML form in PHP File #1, and it is
I have successfully setup my MySQL server to support SSL connections I'm just wondering
I have successfully setup castle windsor using an xml configuration file and everything works

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.