开发者

MS Unit Tests accessing private methods and base class members

开发者 https://www.devze.com 2022-12-21 20:10 出处:网络
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

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 : Control开发者_高级运维ler
{
        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.


You can use the InternalsVisibleTo attribute.

Here's a sample: http://devlicio.us/blogs/derik_whittaker/archive/2007/04/09/internalsvisibleto-testing-internal-methods-in-net-2-0.aspx


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消