如何在C#中进行单元测试中的MapPath

Dav*_*enn 14 c#

我想在单元测试中加载外部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(依赖注入).


zeb*_*box 5

就个人而言,我会非常谨慎地拥有依赖于后端资源存储的任何代码,无论是文件系统还是数据库 - 您在单元测试中引入了一个可能导致漏报的依赖项,即测试失败不是因为你的特定测试代码,而是因为文件不存在或者服务器不可用等等.
请参阅此链接以获取IMO对单元测试的详细定义,更重要的是不是

您的单元测试应该测试一个原子的,明确定义的功能,而不是测试文件是否可以加载.一种解决方案是"模拟"文件加载 - 但是有各种方法,但我个人只是模拟你正在使用的文件系统的接口,而不是尝试做任何完整的文件系统模拟 - 这是一个很好的SO帖子和这是关于文件系统模拟一个很好的SO讨论

希望有所帮助