views:

116

answers:

2

Hi Today I ran into a problem where I cannot call the ControllerContext in my Controller, within the MS Unit Test method when accessing via a private method. For example

//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 ???????????
}

Is there a way to access ControllerContext without modifying the Controller much within Unit Test method?

I need the ControllerContext so I can set the mocked HttpContext for the controller

I tried

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

But compiler throws an error.

Any ideas greatly appreciated.

A: 

That code isn't really unit testable - too many dependencies on static data. Write an integration test and call it a day, or split it into two classes - one which gets the static stuff, and the other which does whatever transformations are necessary.

You might be able to use a 'strong' mocking framework like TypeMock, but I'm not fond of them.

kyoryu