Click here to Skip to main content
15,882,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

When i am running my Unit Test project,so its getting error from mvc application"
System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Web.HttpContext.Current.get returned null.
"

I have tried in MVC Application.
Please help me.

Thanks in Advance.

Ankit Agarwal
Software Engineer

What I have tried:

//Arrange
            GCopaDimensionsController gCopaDimensionsController = new GCopaDimensionsController();
            //gCopaDimensionsController.ControllerContext = context.Object;

            //Act
            ViewResult result = gCopaDimensionsController.Index() as ViewResult;
            //Assert
            Assert.AreEqual("Manage Global Copa Dimension", gCopaDimensionsController.Session["Title"]);
            //Assert.Fail();
Posted
Updated 6-Jul-18 2:37am

1 solution

You get an error but don't tell us what line it is on so I'm not sure what kind of help you are expecting. However from the error message it seems somewhere in the code you haven't posted you are using "System.Web.HttpContext.Current", however your unit test is running in the context of your test runner, not a web server, so there is no HttpContext so .Current will return null.

Not all code is unit testable, in order to make it testable you have to write it in a way that doesn't rely directly on external environmental things like databases, files, http context etc.

To make your code testable you'll need to refactor it so things like access to the Session are abstracted using interfaces and dependency injection which will allow your unit tests to mock the Session for testing purposes. If you google "asp.net unit test session" you'll probably find examples of the kind of things you need to do. Making your code unit testable is not a trivial task.
 
Share this answer
 
Comments
Agarwal1984 9-Jul-18 0:22am    
Actually my error in my controller-
System.Web.HttpContext.Current.Session["Title"] = "Manage Global Copa Dimension";

Session value is not passing in this session.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900