【问题标题】:Unit testing an MVC action method with a Cache dependency?单元测试具有缓存依赖项的 MVC 操作方法?
【发布时间】:2011-04-29 04:27:52
【问题描述】:

我对测试和 MVC 还比较陌生,今天遇到了一个症结所在。我正在尝试测试一个依赖于 HttpContext.Current.Cache 的操作方法,并且想知道实现“低耦合”以简化测试的最佳实践。这是我到目前为止所得到的......

 public class CacheHandler : ICacheHandler
 {
    public IList<Section3ListItem> StateList
    {
        get { return (List<Section3ListItem>)HttpContext.Current.Cache["StateList"]; }
        set { HttpContext.Current.Cache["StateList"] = value; }
    }
 ...

然后我像这样访问它...我将 Castle 用于我的 IoC。

public class ProfileController : ControllerBase
{
    private readonly ISection3Repository _repository;
    private readonly ICacheHandler _cache;

    public ProfileController(ISection3Repository repository, ICacheHandler cacheHandler)
    {
        _repository = repository;
        _cache = cacheHandler;
    }

    [UserIdFilter]
    public ActionResult PersonalInfo(Guid userId)
    {
        if (_cache.StateList == null)
            _cache.StateList = _repository.GetLookupValues((int)ELookupKey.States).ToList();
   ...

然后在我的单元测试中,我可以模拟 ICacheHandler。

这会被视为“最佳实践”吗?是否有人对其他方法有任何建议?

【问题讨论】:

  • 我会质疑谁应该负责检查缓存。控制器真的是最好的地方吗?它只需要一个 StateList。

标签: c# asp.net-mvc caching dependency-injection mocking


【解决方案1】:

推荐的方法是存根HttpContextBase。它的文档说明

当你执行单元测试时,你 通常使用派生类 实现成员自定义 满足场景的行为 你正在测试。

这主要用于 TypeMock here

var httpContext = MockRepository.GenerateStub<HttpContextBase>();
httpContext.Stub(x=>x.Cache).Return(yourFakeCacheHere);

var controllerContext = new ControllerContext(httpContext, ....);

var controller = new HomeController();
controller.ControllerContext = controllerContext;

【讨论】:

    【解决方案2】:

    您隐藏了一个特定的、难以测试的 API (HttpContext.Current) 和接口,并使用 Constructor Injection 将依赖项注入消费者。这或多或少是 教科书 DI(不过,我会在构造函数中添加保护子句)。

    如果您在 Visual Studio 中创建一个新的 ASP.NET MVC 项目,您会看到在 AccountController.cs 文件中,正在执行非常类似的操作来隐藏 MembershipProvider。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 2019-03-21
      • 1970-01-01
      相关资源
      最近更新 更多