Mocking the HttpContext in a ServerControl

6 posts, 0 answers
  1. Steve
    Steve avatar
    1851 posts
    Member since:
    Dec 2008

    Posted 12 Jul 2011 Link to this post

    Ok, so we have an asp.net server control

    The server control internally calls a method to Load the Authenticated User.  It HAD System.Web.HttpContext.Current hardcoded in this method, but I extracted that out to a property to allow me to pass in my own mocked version (I assume thats what JustMock does)?

    protected override MppProfile GetAuthenticatedProfile()
    {
        if (this.LoadAuthenticated && _authenticatedProfile == null) {
            try
            {
                if (this.Context.User != null)
                {
                    try {
                        foreach (MembershipProvider mp in Membership.Providers) {
                            MembershipUser user = mp.GetUser(Context.User.Identity.Name, false);
                            if (user != null) {
                                _authenticatedProfile = AuthDBContext.MppProfiles.SingleOrDefault(x => x.AspnetUser.UserName == user.UserName);
                                break;
                            }
                        }
                    } catch (ConfigurationErrorsException ex) {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        throw new Exception(ex.BareMessage);
                    }
                }
            }
            catch (ArgumentException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                // No authenticated user
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw new InvalidOperationException("Membership must be configured to load the authenticated user. Either configure a membership provider or set LoadAuthenticated=false.");
            }
        }
        return _authenticatedProfile;
    }

    So the question is...how do I go about Mocking this?  Because I need this Unit Test to pass :)  I want GetAuthenticatedProfile to return me an MppProfile object of my choosing as this test doesnt need to go through all of the MembershipUser bits.

    Am I even doing this right?  Should it be simpler in that I pass in an isTest bool and just ignore this part of the method if isTest is true?
  2. Steve
    Steve avatar
    1851 posts
    Member since:
    Dec 2008

    Posted 12 Jul 2011 Link to this post

    This is my current attempt I guess...

    So I found that I can mock an protected method?  But it's still being internally called by the ProfileManager instead of using the Mocked version.

    [TestMethod]
    public void Medportal_ProfileManager_Create() {
        ProfileManager manager = new ProfileManager();
        Mock.NonPublic.Arrange<MppProfile>(manager, "GetAuthenticatedProfile").Returns(manager.AuthDBContext.MppProfiles.Get("steve@medportal.ca"));
     
        Assert.IsNotNull(manager);
     
        //Set the User
        manager.Username = "steve@medportal.ca";
         
        //Validate we have a profile
        manager.LoadAuthenticated = false;
        Assert.IsNotNull(manager.Profile);
    }


  3. DevCraft R3 2016 release webinar banner
  4. Steve
    Steve avatar
    1851 posts
    Member since:
    Dec 2008

    Posted 13 Jul 2011 Link to this post

    Oh wait...I think I forgot

    var manager = Mock.Create<ProfileManager>();

    Seems to be mocking now...cool :)

    Now how can I fake the HttpContext still though?

    **EDIT** Apparently I shouldn't

    Some little known facts about HttpContext:

    • HttpContext is the largest object ever created by humans.
    • If you printed out the code for everything in HttpContext, the pages could be stacked end to end to wrap around the Earth's equator 7 times.
    • Mocking HttpContext is like trying to calculate the last digit of pi.  There is always a little more to it. 
    • Chuck Norris gave up trying to mock HttpContext.  He was deep in HttpContext.Response and quit, curled into a ball on the floor, and started whimpering.
  5. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 15 Jul 2011 Link to this post

    Hi Steve,

    Thanks again for sending the issue. It is great that you are able to solve the issue. However, since "GetAuthenticatedProfile" is protected virtual method once you do Mock.Create it does the mocking via dynamic proxy but you should be able to mock it partially as well just by creating a new instance of the ProfileManager class. Please take a look into the new Q2 build for that.

    In case of "HttpContext" there are still some issues with MockClassAttribute and mocking it from a class other than initiated (passed the instance) from the test class itself but we are looking forward to provide a fix for it at earliest possible.


    KInd Regards,
    Mehfuz
    the Telerik team

    Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

  6. Steve
    Steve avatar
    1851 posts
    Member since:
    Dec 2008

    Posted 15 Jul 2011 Link to this post

    Thank Mehfuz,
      Hey I don't know if this is even a "thing" to do...but judging by all the google posts I've found.  You guys could get a ton more buisness by providing an out-of-the-box configurable Mocked HttpContext object to use...but I'm very new to mocking...so this is just a wishlist thing for me ;)

    Steve
  7. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 21 Jul 2011 Link to this post

    Hi Steve,

    Thanks again for the reply. Little i can tell here that we would love to implement your wish list. Therfore keep them coming.

    Kind regards,
    Mehfuz
    the Telerik team

    Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

Back to Top
DevCraft R3 2016 release webinar banner