【发布时间】:2009-07-31 18:43:42
【问题描述】:
考虑 .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()处将这个虚假与我对静态方法的调用联系起来? - 您对如何改进此代码/架构有任何建议吗?
【问题讨论】:
标签: c# unit-testing mocking moq