开发者

MVC ASP.NET - Unit Test with MOQ for User.Identity.Name in Custom HTML Helper

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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜