0

I have following class in my project

 public class Data
    {
         public void Getdata(){
            var user =  HttpContext.User.Identity.Name;
        }
    } 

It is showing null reference exception

It works nicely for Controller, but not for class as Class does not have ControllerContext . Any help?

6
  • public class Data() { var user = HttpContext.User.Identity.Name; } is it typo? Commented May 25, 2015 at 13:26
  • @AndrewWhitaker It is in method Commented May 25, 2015 at 13:28
  • @KhanhTO i have done it for Controller. I want it for class Commented May 25, 2015 at 13:30
  • it should be HttpContext.Current, right? stackoverflow.com/questions/4379450/… Commented May 25, 2015 at 13:32
  • @KhanhTO Controller has ControllerContext so we can set up fake context. But do i do it for class? Commented May 25, 2015 at 13:33

1 Answer 1

2

You could restructure your class a little to test it in a similar way. One way would be to add a constructor that accepts an HttpContextBase:

public class Data
{
    private HttpContextBase contextBase;

    public Data(HttpContextBase context)
    {
        this.context = context;
    }

    public Data() : this(new HttpContextWrapper(HttpContext.Current))
    {
    }

    public void GetData()
    {
        var user = this.context.User.Identity.Name
    }
}

Then you could pass in your mocked HttpContextBase during your unit test.

[TestMethod]
public void Test()
{
    var fakeHttpContext = new Mock<HttpContextBase>();
    var fake = new GenericIdentity("user");
    var prin = new GenericPrincipal(fakeIdentity, null);

    fakeHttpContext.Setup(t => t.User).Returns(prin);

    var data = new Mock<Data>(fakeHttpContext.Object);

    // Now you can successfully call data.GetData()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.