相关疑难解决方法(0)

Moq:单元测试依赖于HttpContext的方法

考虑.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;      
}
Run Code Online (Sandbox Code Playgroud)

我想使用Moq框架从单元测试中调用此方法.该程序集是webforms解决方案的一部分.单元测试看起来像这样,但我错过了Moq代码.

//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.");
Run Code Online (Sandbox Code Playgroud)

问题:

  • 我如何使用Moq来安排假的HttpContext对象,其值如'MyDomain\MyUser'?
  • 如何将我的调用与我的调用关联到静态方法中MyIdentityBL.GetSecurityContextUserName()
  • 您对如何改进此代码/架构有任何建议吗?

c# unit-testing moq mocking

38
推荐指数
1
解决办法
3万
查看次数

标签 统计

c# ×1

mocking ×1

moq ×1

unit-testing ×1