我想在单元测试中加载外部XML文件,以测试该XML上的一些处理代码.如何获取文件的路径?
通常在Web应用程序中我会这样做:
XDocument.Load(Server.MapPath("/myFile.xml"));
Run Code Online (Sandbox Code Playgroud)
但显然在我的单元测试中我没有引用Server或HttpContext,那么如何映射路径以便我不必指定完整路径?
更新:
我只想说明我实际测试的代码是针对XML解析器类的,类似于:
public static class CustomerXmlParser {
public static Customer ParseXml(XDocument xdoc) {
//...
}
}
Run Code Online (Sandbox Code Playgroud)
所以为了测试这个,我需要解析一个有效的XDocument.正在测试的方法不会访问文件系统本身.我可以直接在测试代码中从String创建XDocument,但我认为从文件加载它会更容易.
kas*_*ter 24
另一个想法是利用依赖注入.
public interface IPathMapper {
string MapPath(string relativePath);
}
Run Code Online (Sandbox Code Playgroud)
然后简单地使用2个实现
public class ServerPathMapper : IPathMapper {
public string MapPath(string relativePath){
return HttpContext.Current.Server.MapPath(relativePath);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你还需要你的模拟实现
public class DummyPathMapper : IPathMapper {
public string MapPath(string relativePath){
return "C:/Basedir/" + relativePath;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你需要映射路径的所有函数只需要访问一个IPathMapper实例 - 在你的web应用程序中它需要是ServerPathMapper,并在你的单元中测试DummyPathMapper - 基本DI(依赖注入).