开发者

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

开发者 https://www.devze.com 2023-02-28 15:08 出处:网络
Experts I\'ve a simple HTML Helper method below. Could anyone tell me how to mock the user.identity.name on this scenario:

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

精彩评论

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