0

I want to test my project using visual studio unit test but it produce error of null reference of User.Identity.GetUserID() is there any way to mock it or I have to logged-in through unit test. I have searched a lot but not found the solution.

here is code to be tested

 public PartialViewResult _AdmitPatient(int id)
        {
            if (cFunctions.AllowAccessToRecord((int)id, User.Identity.GetUserId(), "patient") == false)
            {
                return null;
            }
            Admission admission = new Admission();
            admission.PatientID = id;
            return PartialView(admission);
        } 

Here is unit test for this code

 [TestMethod]
        public void TestAdmitPatView()
        {
            var adc = new AdmissionController();

            var res = adc._AdmitPatient(6);


            Assert.AreEqual(adm.PatientID, res.ViewData);

        }

if I have to create logged-in in unit test kindly tell me in detail how to be logged-in

  • You should separate your logic from your controller and test it from there. Testing controllers is hard because you are not using http requests to call them. – jamesSampica Mar 17 '15 at 18:14
  • please kindly tell me how it should be tested I am querying the same what you answered i get null reference so how could i get value and I think I have to log in from test into controller if this is the solution then please tell me how to login and add claims in test – Syed Anwar Shah Tarn Mar 18 '15 at 08:47
  • You need to mock your identity with a specific claim. See my answer here http://stackoverflow.com/a/39898952/2672291 – Haohmaru Oct 06 '16 at 15:07

1 Answers1

2

HttpContext.User Property is working on the hosted application. This will be null in tests environment. Because HttpContext.User is not set by test frameworks. SO you should create a fake object via mocking frameworks like Fakeiteasy, or Moq

If you are using FakeItEasy, you can create object:

[TestMethod]
public void TestAdmitPatView()
{
    var adc = new AdmissionController();

    adc.ControllerContext = A.Fake<ControllerContext>();
    var fakePrincipal = A.Fake<IPrincipal>();
    var fakeIdentity = new GenericIdentity( "username" );
    A.CallTo( () => fakePrincipal.Identity ).Returns( fakeIdentity );
    A.CallTo( () => HomeController.ControllerContext.HttpContext.User ).Returns( fakePrincipal );

    var res = adc._AdmitPatient(6);

    Assert.AreEqual(adm.PatientID, res.ViewData);
}

if your cFunctions.AllowAccessToRecord method is calling database, you should fake it also.