C#单元测试:测试使用的MapPath方法单元测试、测试、方法、MapPath

2023-09-03 10:48:27 作者:多的是你不知道的事@

首先,我知道这个问题是危险地接近: http://stackoverflow.com/questions/1231860/how-to-mappath-in-a-unit-test-in-c

First of all, I am aware that this question is dangerously close to: http://stackoverflow.com/questions/1231860/how-to-mappath-in-a-unit-test-in-c

林然而希望,它有一个不同的解决方案。我的问题如下:

I'm hoping however, that it has a different solution. My issue follows:

在我的code我有一个对象,有待进一步验证。我创建单元测试,每个验证方法,以确保它是正确验证。我创建模拟数据,并加载到对象,然后验证它。的问题是,在验证中,当发生错误时,错误code为分配。此错误code,以便收集有关使用使用Server.Mappath一个XML文件中的错误信息。然而,试图获得XML文件时,抛出一个异常表示文件无法找到。

In my code I have an object that needs to be validated. I am creating unit tests for each validation method to make sure it is validating correctly. I am creating mock data and loading it into the object, then validating it. The problem is that within the validation, when an error occurs, an error code is assigned. This error code is used to gather information about the error from an xml file using Server.MapPath. However, when trying to get the xml file, an exception is thrown meaning the file cannot be found.

由于MapPath的是我的验证code,而不是我的单元测试,如何让我的单元测试来识别路径?请问这个问题有意义吗?

Since MapPath is in my validation code, and not my unit test, how do I get my unit test to recognize the path? Does this question make sense?

错误行(在我的验证code不是我的单元测试):

Error Line (In my Validation code NOT my unit test):

XDocument xdoc = XDocument.Load(HttpContext.Current.Server.MapPath("App_Data/ErrorCodes.xml"));

简体:单元测试调用我的程序调用它使用Server.Mappath然后失败的方法

Simplified: The Unit Test calls a method in my program that calls Server.MapPath which then fails.

推荐答案

我要抽象出来的​​文件名提供成类,只是返回一个位置,那么你就可以多嘲笑它,容易多了。

I would abstract out the "filename provider" into an class that simply returns a location, then you can mock it much, much easier.

public class PathProvider
{
    public virtual string GetPath()
    {
        return HttpContext.Current.Server.MapPath("App_Data/ErrorCodes.xml");
    }
}


PathProvider pathProvider = new PathProvider();
XDocument xdoc = XDocument.Load(pathProvider.GetPath());

当然,这是一个非常简单的(因此很可能不是最好的)解决方案,但一开始在正确的方向。

Granted, this is a very simple (so likely not the best) solution, but a start in the right direction.