【问题标题】:MS Unit Tests accessing private methods and base class members访问私有方法和基类成员的 MS 单元测试
【发布时间】: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


    【解决方案1】:
    【解决方案2】:

    该代码并不是真正的单元测试 - 对静态数据的依赖过多。编写一个集成测试并收工,或者将其拆分为两个类 - 一个获取静态内容,另一个进行任何必要的转换。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多