Bartosz
Bartosz

Reputation: 4592

mocking User.Identity.Name in MVC4

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?

Upvotes: 0

Views: 1530

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Your code throws exception when you are getting user name. User returns 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:

public IPrincipal User
{
    get
    {
        if (HttpContext != null)            
            return HttpContext.User;

        return null;
    }
}

So, as you see, without HttpContext it returns null. Thus you need to setup HttpContext and provide mocked IPrincipal for your test. See here how to create fake HttpContext.

Upvotes: 0

DevDave
DevDave

Reputation: 6888

This may not solve your moq problem but for what its worth, MvcContrib Test Helper is very useful for mocking a logged in user.

Using Test Helper you can write code like this:

FakeIdentity FakeId = new FakeIdentity(UserName);
FakeUser = new FakePrincipal(FakeId, new[] {  "Admin" });   
Thread.CurrentPrincipal = FakeUser;

to mock a user. Hope this helps.

Upvotes: 1

Related Questions