2010-03-05 69 views
1

今天我遇到了一个问题,我无法在通过私有方法访问MS MS单元测试方法时在我的控制器中调用ControllerContext。例如MS单元测试访问私有方法和基类成员

//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,而无需在单元测试方法中修改控制器?

我需要ControllerContext,所以我可以设置嘲笑的HttpContext为控制器

我试图

((SampleController)privateAcc).ControllerContext = this.GetControllerContext(); 

但是编译器会引发错误。

任何想法非常感谢。

回答

0

该代码是不是真的单元测试 - 静态数据太多的依赖。编写一个集成测试并在一天内调用它,或者将其分成两个类 - 一个获取静态内容,另一个执行任何必要的转换。

你也许可以使用像TypeMock这样的强大的模拟框架,但我并不喜欢它们。