I am trying to write a test for one of my methods in controller (MVC4). I use Moq. Within the test method I create a mock for my repository like so:
Mock<ISurveyRepository> mock = new Mock<ISurveyRepository>();
and proceed with mocking up repository calls. First one of those is:
int userId = repository.GetUserId(User.Identity.Name);
So I add this to my test method:
mock.Setup(y => y.GetUserId("testName")).Returns(1);
Unfortunatelly this line of code gives me:
System.NullReferenceException: Object reference not set to an instance of an object.
If I remove the line above from my controller and use static value instead (int userId = 1) a test completes fine.
Can anyone tell me why?
Your code throws exception when you are getting user name.
Userreturns security information from current HTTP request. During test you don’t have HTTP request, thus this code throws an exception.Here is an implementation of this property:
So, as you see, without HttpContext it returns null. Thus you need to setup HttpContext and provide mocked
IPrincipalfor your test. See here how to create fake HttpContext.