【发布时间】:2011-12-07 01:44:09
【问题描述】:
今天我遇到了一个问题,当通过私有方法访问时,我无法在 MS 单元测试方法中调用 Controller 中的 ControllerContext。例如
//This is my controller and private GetUsers() method
public class SampleController : Controller
{
private IEnumerable<Users> GetUsers()
{
try
{
string cacheKey = "UserKey";
IList<User> users;
if (this.HttpContext.Cache[cacheKey] != null)
{
users= (IList<User>)this.HttpContext.Cache[cacheKey];
}
else
{
users= UserService.GetUsers();
if (users!= null)
{
this.HttpContext.Cache.Insert(cacheKey, users, null, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
}
}
return UserExtensions.GetModifiedUsers(users);
}
catch (Exception ex)
{
throw ex;
}
}
}
//In Unit Tests
[TestMethod]
public void SampleTestMethod()
{
SampleController_Accessor privateAcc = new SampleController_Accessor();
privateAcc.ControllerContext //Which is not availble intelliSense ???????????
}
有没有一种方法可以访问 ControllerContext 而无需在单元测试方法中大量修改 Controller?
我需要 ControllerContext 以便为控制器设置模拟的 HttpContext
我试过了
((SampleController)privateAcc).ControllerContext = this.GetControllerContext();
但是编译器会抛出错误。
非常感谢任何想法。
【问题讨论】:
标签: model-view-controller unit-testing controller mstest