Unit testing an MVC action method with a Cache dependency?
Posted
by Steve
on Stack Overflow
See other posts from Stack Overflow
or by Steve
Published on 2010-03-11T21:16:28Z
Indexed on
2010/03/11
21:19 UTC
Read the original article
Hit count: 250
I’m relatively new to testing and MVC and came across a sticking point today. I’m attempting to test an action method that has a dependency on HttpContext.Current.Cache and wanted to know the best practice for achieving the “low coupling” to allow for easy testing. Here's what I've got so far...
public class CacheHandler : ICacheHandler
{
public IList<Section3ListItem> StateList
{
get { return (List<Section3ListItem>)HttpContext.Current.Cache["StateList"]; }
set { HttpContext.Current.Cache["StateList"] = value; }
}
...
I then access it like such... I'm using Castle for my 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();
...
Then in my unit tests I am able to mock up ICacheHandler.
Would this be considered a 'best practice' and does anyone have any suggestions for other approaches?
Thanks in advance.
Cheers
© Stack Overflow or respective owner