How to unit test code that uses HostingEnvironment.MapPath

前端 未结 5 817
走了就别回头了
走了就别回头了 2020-12-31 01:46

I have some code that uses HostingEnvironment.MapPath which I would like to unit test.

How can I setup HostingEnvironment so that it retur

5条回答
  •  一整个雨季
    2020-12-31 02:21

    As i faced same issue i changed my code bit. From

    strhtmlTemplate = File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath(Lgetfilepath.CVal));
    

    To

    strhtmlTemplate = File.ReadAllText(HttpContextFactory.Current.Server.MapPath(Lgetfilepath.CVal));
    

    For Unit test

    public HttpContextBase mockHttpContextBase()
            {
                var moqContext = new Mock();
                var moqRequest = new Mock();
                var moqServer = new Mock();
                var moqPath = new Mock();
                moqContext.Setup(x => x.Request).Returns(moqRequest.Object);
                moqContext.Setup(x => x.Server.MapPath(@"~\Data\xxxxxxx")).Returns(Environment.CurrentDirectory+@"\xxxxxx");                
                setupApplication(moqContext);
    
                return moqContext.Object;
            }
    

    Now we while Writing TestClass you need to refer above method to mock. Hope it will helpful for your TestCases.

    MockDataUT mockData = new MockDataUT();
    var mockRequestContext = new HttpRequestContext();
    HttpContextFactory.SetCurrentContext(mockData.mockHttpContextBase());
    

提交回复
热议问题