Software login with .net membership provider

I am trying to unit test a piece of code that the current user needs in the current session. Using the .Net 2.0 membership provider, how can I programmatically log in as a user for this test?

+7
c # unit-testing membership asp.net-membership
source share
4 answers
if(Membership.ValidateUser("user1",P@ssw0rd)) { FormsAuthentication.SetAuthCookie("user1",true); } 
+13
source share

I found it most convenient to create a one-time class that handles the installation and reset of 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 simply transfer your call using the using statement:

 using (new TemporaryPrincipal(new AnonymousUserPrincipal())) { ClassUnderTest.MethodUnderTest(); } 
+2
source share

Does a user registered through ASP.NET really need your code, or does he just need CurrentPrincipal? I don’t think you need to log in to your site programmatically. You can create a GenericPrincipal , set the properties you need and attach it, for example Thread.CurrentPrincipal or the mocked HttpContext. If your code really needs RolePrincipal or something else, I would modify the code so that it is less associated with ASP.NET membership.

+1
source share

Using your member, you can verify the user using Membership.ValidateUser. You can then set up an authentication cookie using FormsAuthentication.SetAuthCookie. As long as you have a cookie container, this should allow you to log in.

0
source share

All Articles