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

7

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

4个回答

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

2

我发现创建一个一次性类来处理设置和重置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();
}

1

你的代码实际上是否需要通过ASP.NET登录用户,还是只需要一个CurrentPrincipal?我认为你不需要在网站上编程登录。你可以创建一个GenericPrincipal,设置所需的属性,并将其附加到Thread.CurrentPrincipal或模拟的HttpContext等对象上。如果你的代码实际上需要RolePrincipal或其他东西,那么我会更改代码,使其与ASP.NET成员资格耦合度更低。


我需要调用Membership.GetUser()方法来返回当前登录的用户。 - ddc0660
2
不要在测试类中直接调用Membership.GetUser()。在创建时提供一个IGetUser实例,并在使用时替换Membership.GetUser(),然后为测试创建一个IGetUser的模拟实现。 - Craig Stuntz

0

通过使用您的会员提供程序,您可以使用Membership.ValidateUser验证用户。然后,您可以使用FormsAuthentication.SetAuthCookie设置身份验证cookie。只要您有一个cookie容器,这应该允许您登录用户。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接