考虑 .NET 程序集中的一个方法:
public static string GetSecurityContextUserName()
{
//extract the username from request
string sUser = HttpContext.Current.User.Identity.Name;
//everything after the domain
sUser = sUser.Substring(sUser.IndexOf("\\") + 1).ToLower();
return sUser;
}
我想使用 Moq 框架从单元测试中调用此方法。此程序集是 webforms 解决方案的一部分。单元测试看起来像这样,但我缺少最小起订量代码。
//arrange
string ADAccount = "BUGSBUNNY";
string fullADName = "LOONEYTUNES\BUGSBUNNY";
//act
//need to mock up the HttpContext here somehow -- using Moq.
string foundUserName = MyIdentityBL.GetSecurityContextUserName();
//assert
Assert.AreEqual(foundUserName, ADAccount, true, "Should have been the same User Identity.");
问题:
- 我如何使用 Moq 来安排一个具有某些值的假 HttpContext 对象,例如“MyDomain\MyUser”?
- 我如何将那个假货与我对我的静态方法的调用联系起来
MyIdentityBL.GetSecurityContextUserName()
? - 您对如何改进此代码/架构有任何建议吗?