How to unit test code that uses HostingEnvironment.MapPath

前端 未结 5 958
走了就别回头了
走了就别回头了 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:35

    Well I was writing a test today for code that I don't control and they used

        private static String GetApplicationPath()
        {
            return HostingEnvironment.ApplicationVirtualPath.TrimEnd('/');
        }
    

    so here is a C# reflection hack to set that value

    var path =  "/aaaa/bb";
    
    HostingEnvironment hostingEnvironment;
    if (HostingEnvironment.IsHosted.isFalse())
        new HostingEnvironment();
    
    hostingEnvironment = (HostingEnvironment)typeof(HostingEnvironment).fieldValue("_theHostingEnvironment");
    
    var virtualPath = "System.Web".assembly()
                       .type("VirtualPath").ctor();
    
    virtualPath.field("_virtualPath", path);
    //return virtualPath.prop("VirtualPathString");                
    //return virtualPath.prop("VirtualPathStringNoTrailingSlash");                 
    
    hostingEnvironment.field("_appVirtualPath", virtualPath);
    //hostingEnvironment.field("_appVirtualPath") == virtualPath;
    
    return HostingEnvironment.ApplicationVirtualPath == path;       
    
    //using  System.Web.Hosting
    

提交回复
热议问题