1

Experts I've a simple HTML Helper method below. Could anyone tell me how to mock the user.identity.name on this scenario:

public static string GetLoggedUsername(this HtmlHelper helper)
{
    return repo.Name + " - [" + HttpContext.Current.User.Identity.Name + "]";
}

I'm facing object reference not set.... error

I don't know how to pass user.identity.name while unit testing.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
Nil Pun
  • 17,035
  • 39
  • 172
  • 294

1 Answers1

2

Try this:

Replace HttpContext.Current.User.Identity.Name with helper.ViewContext.HttpContext.User.Identity.Name.

You will then create an instance of HtmlHelper in your unit test and mock out its dependencies. Then pass in the HtmlHelper instance as a parameter in your helper function, like so:

        var mockViewContext = new Mock<ViewContext>();
        mockViewContext.Setup(x => x.HttpContext.User.Identity.Name).Returns("TheUser");

        var mockViewDataContainer = new Mock<IViewDataContainer>();

        var helper = new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);

        var output = GetLoggedUsername(helper);

        Assert.AreEqual("RepoName - [TheUser]", output);
John Allers
  • 3,052
  • 2
  • 30
  • 36
  • Thank you John It worked. I will appreciate if you could help me with these queries please. http://stackoverflow.com/questions/5769163/asp-net-mvc-unit-testing-override-initialize-method. And also this one if you don't mind http://stackoverflow.com/questions/5767640/moq-setup-vs-setupget – Nil Pun Apr 24 '11 at 21:32