.net - 如何使 HttpContext 可供我的单元测试使用?

标签 .net asp.net unit-testing httpcontext httpserverutility

我想编写一个单元测试来测试一个名为 UploadedFile 的类的功能。

我面临的问题是这个类的静态构造函数使用 HttpContext.Current 属性,因为我从类库运行我的单元测试,所以我在测试时没有 HttpContext 。

看看我的静态构造函数:

static UploadedFile()
{
    if (HttpContext.Current == null)
        throw new Exception("web server not available");

    HttpServerUtility server = HttpContext.Current.Server;

    // SET UploadedFileMappingFile Names:
    _resourceFileNames = new StringDictionary();

    _resourceFileNames[_suppoertedFileStructures] = server.MapPath(SupportedUploadedFileStructures);
    _resourceFileNames[_supportedFileStructuresXSD] = server.MapPath(SupportedUploadedFileStructuresXSD);

    _resourceFileNames[UploadedFileEnum.UploadedFileFormatENUM.CSV.ToString()] = server.MapPath(UploadedFileColumnMap);        
}

我应该在我的测试环境中做什么,以便 HttpContext.Current不会为空,我可以成功设置:
 HttpServerUtility server = HttpContext.Current.Server;

最佳答案

你不应该使用 HttpContext.Current正如您已经发现的那样,直接在您的函数中进行单元测试几乎是不可能的。我建议你使用 HttpContextBase相反,它在您的类的构造函数中传递或作为您正在测试的方法的参数传递。这将允许这个类的消费者传递一个真正的 HttpContextWrapper在你的单元测试中,你可以模拟你需要的方法。

例如,您可以通过以下方式调用该方法:

var wrapper = new HttpContextWrapper(HttpContext.Current);
Foo.UploadedFile(wrapper);

在您的单元测试中(使用 Rhino Mocks ):
var contextMock = MockRepository.GenerateMock<HttpContextBase>();
// TODO: Define expectations on the mocked object
Foo.UploadedFile(contextMock);

或者,如果您愿意,可以使用 Constructor Injection .

关于.net - 如何使 HttpContext 可供我的单元测试使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475326/

相关文章:

.net - 将插入符号放置在MaskedTextbox中

c# - 序列化包含 StateServer 的 linq2sql 对象的对象

.net - 如何从 $(ProjectDir) 中删除结尾的反斜杠?

javascript - 我可以在ajax运行时刷新页面而不杀死它吗?

javascript - Window.open 作为模态弹出窗口?

python - 一段python代码如何判断它是否在unittest下运行

multithreading - 如何测试跨线程队列?

c# - 单字节顺序

c# - 在 rowcommand 上发送 HTTP header 后,服务器无法设置内容类型

flutter - Dart/Flutter Web 单元测试错误 : Error: Not found: 'dart:html'