This is a migrated thread and some comments may be shown as answers.

Mocking the HttpContext in a ServerControl

5 Answers 138 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
sitefinitysteve
Top achievements
Rank 2
Iron
Veteran
sitefinitysteve asked on 12 Jul 2011, 06:51 PM
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?

5 Answers, 1 is accepted

Sort by
0
sitefinitysteve
Top achievements
Rank 2
Iron
Veteran
answered on 12 Jul 2011, 07:55 PM
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);
}


0
sitefinitysteve
Top achievements
Rank 2
Iron
Veteran
answered on 13 Jul 2011, 02:10 PM
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.
0
Ricky
Telerik team
answered on 15 Jul 2011, 11:37 AM
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!

0
sitefinitysteve
Top achievements
Rank 2
Iron
Veteran
answered on 15 Jul 2011, 06:00 PM
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
0
Ricky
Telerik team
answered on 21 Jul 2011, 09:20 AM
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!

Tags
General Discussions
Asked by
sitefinitysteve
Top achievements
Rank 2
Iron
Veteran
Answers by
sitefinitysteve
Top achievements
Rank 2
Iron
Veteran
Ricky
Telerik team
Share this question
or