【发布时间】: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