Search code examples
asp.netunit-testingvs-unit-testing-framework

"HttpContext.Current.User" is null, when it is access through unit test method


In my method I am getting the current user by using "HttpContext.Current.User".Like this

public class Test
{
public UserPrincipal GetUserContext()
 {
   System.Security.Principal.IPrincipal user = HttpContext.Current.User;
   return user;
 }
}

In Test method i am accessing like this,

[TestMethod()]
public void TestMethod()
{
Test objTest = new Test();
System.Security.Principal.IPrincipal user=objTest.GetUserContext()
}

while running this test method i am having exception because of "HttpContext.Current.User" is null

Can anyone familiar with this issue. Thanks in advance.


Solution

  • This code will create fake HttpContext:

        string UserName = "username";
        HttpContext.Current = new HttpContext(
                              new HttpRequest("", "http://tempuri.org", ""),
                              new HttpResponse(new StringWriter()));
        HttpContext.Current.User = new GenericPrincipal(
                                   new GenericIdentity(UserName),new string[0]);