How to unit test code that uses HostingEnvironment.MapPath

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

    Just use this code..

    Make a new folder name Reference in root directory and added your file inside this folder.

    Use this

    public static XElement GetFile()
    {
        HttpContext.Current = new HttpContext(new HttpRequest("", "http://www.google.com", ""), new HttpResponse(new StringWriter()));
    
        var doc = new XmlDocument();
        var file = HttpContext.Current.Server.MapPath("\\") + "abc.xml";
        doc.Load(file);
        var e = XElement.Load(new XmlNodeReader(doc));
        return e;
    }
    

提交回复
热议问题