Richa
Richa

Reputation: 3289

Unit test Class in MVC

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?

Upvotes: 0

Views: 79

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

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()
}

Upvotes: 2

Related Questions