如何在C#中的单元测试的MapPath [英] How to MapPath in a unit test in C#
问题描述
我要加载外部XML文件中的一个单元测试来测试上一些XML处理代码。 ?如何获取该文件的路径
I want to load an external XML file in a unit test to test some processing code on that XML. How do I get the path of the file?
通常在一个web应用程序,我会做:
Usually in a web app I would do:
XDocument.Load(Server.MapPath("/myFile.xml"));
但很明显,在我的单元测试我有没有提到服务器或HttpContext的,所以我怎么能映射路径?这样我就不必指定完整路径
But obviously in my unit test I have no reference to Server or HttpContext so how can I map a path so that I don't have to specify the full path?
更新:
我只想说清楚,我实际测试的代码是一个XML解析器类,是这样的:
I just want to make it clear that the code I'm actually testing is for an XML parser class, something like:
public static class CustomerXmlParser {
public static Customer ParseXml(XDocument xdoc) {
//...
}
}
因此,为了测试这个我需要解析一个有效的XDocument。被测试的方法不访问文件系统本身。我可以从一个字符串直接在测试代码创建的XDocument,但我认为这将是容易只是从文件中加载它。
So to test this I need to parse a valid XDocument. The method being tested does not access the file system itself. I could create the XDocument from a String directly in the test code but I thought it would be easier to just load it from a file.
推荐答案
另一个想法是利用依赖注入。
Another idea would be to utilize dependency injection.
public interface IPathMapper {
string MapPath(string relativePath);
}
,然后只需用2实施
And then simply use 2 implementations
public class ServerPathMapper : IPathMapper {
public string MapPath(string relativePath){
return HttpContext.Current.Server.MapPath(relativePath);
}
}
和则还需要你的模拟实现。
And then you also need your mock implementation
public class DummyPathMapper : IPathMapper {
public string MapPath(string relativePath){
return "C:/Basedir/" + relativePath;
}
}
然后所有的功能需要映射路径的会只需访问IPathMapper的一个实例 - 在你的web应用程序,它需要是ServerPathMapper和单元测试的DummyPathMapper - 基本DI(依赖注入)
And then all your functions that needs to map path's would simply need to have access to an instance of IPathMapper - in your web app it needs to be the ServerPathMapper and in your unit tests the DummyPathMapper - basic DI (Dependency Injection).
这篇关于如何在C#中的单元测试的MapPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!