使用.net成员资格提供程序进行编程登录

我正在尝试对测试中需要当前登录用户的一段代码进行unit testing。 使用.Net 2.0成员资格提供程序,如何以编程方式以此用户身份登录此测试?

if(Membership.ValidateUser("user1",P@ssw0rd)) { FormsAuthentication.SetAuthCookie("user1",true); } 

我发现创建一个处理设置和重置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; } } 

在测试方法中,您只需使用如下的using语句包装您的调用:

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

您的代码是否确实需要通过ASP.NET登录的用户,还是只需要一个CurrentPrincipal? 我认为您不需要以编程方式登录到您的站点。 您可以创建GenericPrincipal ,设置所需的属性,并将其附加到,例如Thread.CurrentPrincipal或模拟的HttpContext。 如果您的代码实际上需要RolePrincipal或其他什么,那么我会将代码更改为与ASP.NET成员资格相关联。

使用您的成员资格提供程序,您可以使用Membership.ValidateUservalidation用户。 然后,您可以使用FormsAuthentication.SetAuthCookie设置身份validationcookie。 只要你有一个cookie容器,这应该允许你登录用户。