7

我正在尝试对在测试中需要当前登录用户的一段代码进行单元测试。使用 .Net 2.0 Membership Provider,我如何以编程方式以用户身份登录此测试?

4

4 回答 4

13
if(Membership.ValidateUser("user1",P@ssw0rd))
        {
            FormsAuthentication.SetAuthCookie("user1",true); 
}
于 2009-07-10T19:33:32.987 回答
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();
}
于 2008-10-30T16:18:09.787 回答
1

您的代码实际上需要通过 ASP.NET 登录的用户,还是只需要 CurrentPrincipal?我认为您不需要以编程方式登录您的网站。您可以创建一个GenericPrincipal,设置您需要的属性,并将其附加到,例如 Thread.CurrentPrincipal 或模拟的 HttpContext。如果您的代码实际上需要 RolePrincipal 或其他东西,那么我会更改代码以减少与 ASP.NET 成员身份的耦合。

于 2008-10-28T19:19:52.963 回答
0

使用 Membership Provider,您可以使用 Membership.ValidateUser 验证用户。然后,您可以使用 FormsAuthentication.SetAuthCookie 设置身份验证 cookie。只要您有一个 cookie 容器,这应该允许您登录用户。

于 2008-10-28T19:48:04.420 回答