Need help with writing a unit test for code that uses HttpContext.Current.Session

I have a working application for which I need to now add a full set of unit tests. The current code stores the user information as follows:

HttpContext.Current.Session["UserInfo"] = userData; 

I'm using moq for my testing, and my unit test has the following code:

var server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose); var response = new Mock<HttpResponseBase>(MockBehavior.Strict); var request = new Mock<HttpRequestBase>(MockBehavior.Strict); var context = new Mock<HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); context.SetupGet(x => x.Response).Returns(response.Object); context.SetupGet(x => x.Server).Returns(server.Object); var controller = new LoginController(); controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller); JsonResult result = controller.LoginUser( new LoginHelper { userName = "myusername", password = "invalidpassword" } ) as JsonResult; 

Of course when I get to where the login process tries to create the session data, I get an "Object reference not set to an instance of an object." error becuase HttpContext.Current is null.

Some research has shown me that using Current isn't exactly compatible with MSTest, so I understand that I might need to change the way I store/load my user information. However, I would like some advice on which way to go here.

I would appreciate any suggestions on either how to get my unit tests to work, or a different method to store the user info to make it more compatible with unit tests.

by esdictor via /r/csharp

Leave a Reply