2023-02-16 322
我正在尝试单位测试需要在测试中使用当前登录用户的代码.使用.NET 2.0成员资格提供程序,如何以用户为用户编程方式登录此测试?
if(Membership.ValidateUser("user1",P@ssw0rd))
{
FormsAuthentication.SetAuthCookie("user1",true);
}
我发现最方便,创建处理设置和重置线程的一次性类.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 (new TemporaryPrincipal(new AnonymousUserPrincipal())) {
ClassUnderTest.MethodUnderTest();
}
您的代码实际上需要通过ASP.NET登录的用户,或者它只需要一个CurrentPrincipal?我不认为您需要以编程方式登录您的网站.您可以创建一个 genericprincipal ,设置您需要的属性,并将其附加到,例如thread.currentprincipal或模拟的httpContext.如果您的代码实际上需要角色透明构件或某事,那么我将更改代码,以较少耦合到ASP.NET成员资格.
以上所述是小编给大家介绍的使用.net会员制的程序化登录,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/33879.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态