0

I am writing test cases using the Unit Test for ASP.NET MVC 3 with Web Api.

Now I have an action which makes a call to some method I have defined in the service layer, where I have used the following line of code.

var userId = ((Project)(User.Identity)).UserId;

where Project class is

using System;
using System.Security.Principal;
using System.Web.Security;



namespace Project.Web.Core.Models
{ 
[Serializable]
public class ProjectUser : IIdentity
{
    public ProjectUser(){} 
    public int UserId { get; set; }
  }
}

Now how to I create unit test method for this, I am getting null reference exceptions. I am new to writing unit test Can anyone please help me

User_18
  • 59
  • 1
  • 9
  • Ideally you should be mocking external service calls or for that matter anything external to your program when writing unit tests. Mocking in short is to replace the external service with your own test service or even hardcoded values for the purpose of unit test. A search can give you more details on how to create mocks depending on the unit test framework or tool that you are using. – Ravi Y Nov 22 '12 at 06:25
  • So you are telling like i should mock IIdentity??? – User_18 Nov 22 '12 at 06:28
  • I was referring to this part Now "I have an action which makes a call to some method I have defined in the service layer,". YOu should mock the service call and the return values from the service. That way you can unit test your "action" with whatever return values you get. – Ravi Y Nov 22 '12 at 06:30
  • On a side note, if and only if the null reference errors are coming from your action code because of the unit test, then your action needs some tweaking to handle nulls. It would also mean that your unit test has served its usefulness to some extent. – Ravi Y Nov 22 '12 at 06:31

1 Answers1

0

Similar to this question: Testing controller Action that uses User.Identity.Name

The HttpContext in which the User.Identity object does not exist within the context of a Unit test, it only exists within the context of code running within the ASP.NET process.

It might make it easier to write a unit test if you passed the HttpContext as a parameter to your service methods. Then you could use code similar to this answer to the referenced question:

var mock = new Mock<UnknownServiceClass>();
var mockedUser = new ProjectUser(){ UserId = 1 };
mock.SetupGet(p => p.HttpContext.User).Returns(mockedUser);
Community
  • 1
  • 1
user1225352
  • 237
  • 3
  • 13