programmatic login with .net membership provider

11,931

Solution 1

I've found it most convenient to create a disposable class that handles setting and resetting Thread.CurrentPrincipal.

    public class TemporaryPrincipal : IDisposable {
        private readonly IPrincipal _cache;

        public TemporaryPrincipal(IPrincipal tempPrincipal) {
            _cache = Thread.CurrentPrincipal;
            Thread.CurrentPrincipal = tempPrincipal;
        }

        public void Dispose() {
            Thread.CurrentPrincipal = _cache;
        }
    }

In the test method you just wrap your call with a using statement like this:

using (new TemporaryPrincipal(new AnonymousUserPrincipal())) {
    ClassUnderTest.MethodUnderTest();
}

Solution 2

Does your code actually need a user logged in via ASP.NET, or does it just need a CurrentPrincipal? I don't think you need to programmatically log in to your site. You can create a GenericPrincipal, set the properties you need, and attach it to, for example Thread.CurrentPrincipal or a mocked HttpContext. If your code actually needs RolePrincipal or something then I would change the code to be less coupled to ASP.NET membership.

Share:
11,931
ddc0660
Author by

ddc0660

I'm a developer for Parse3 in Warwick, NY. @ddc0660

Updated on June 04, 2022

Comments

  • ddc0660
    ddc0660 almost 2 years

    I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?

  • ddc0660
    ddc0660 over 15 years
    I need the call to Membership.GetUser() to return the currently logged in user.
  • Kevin Gauthier
    Kevin Gauthier over 15 years
    Don't call Membership.GetUser() directly in the class under test. Supply the class with an IGetUser in creation, use it in place of Membership.GetUser(), then make a mock implementation of IGetUser for testing.