如何使HttpContext可供单元测试使用? [英] How can I make HttpContext available to be used by my Unit Tests?

查看:140
本文介绍了如何使HttpContext可供单元测试使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个单元测试,以测试称为UploadedFile的类的功能。

I want to write a unit test which tests the function of a class called UploadedFile.

我面临的问题是此类的静态构造函数使用HttpContext.Current属性,并且由于我正在从类库中运行单元测试,因此在该类中没有HttpContext测试时间。

The problem I face is this class' static constructor uses HttpContext.Current property and because I am running my unit test from a class library I do not have an HttpContext at the testing time.

看一下我的静态构造函数:

Look at my static constructor:

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 不会为空,我可以成功设置为:

What should I do in my testing environment so that HttpContext.Current won't be null and I can successfully set this:

 HttpServerUtility server = HttpContext.Current.Server;


推荐答案

您不应使用 HttpContext.Current 直接在您的函数中,因为您已经发现它几乎不可能进行单元测试。我建议您使用 HttpContextBase 代替,在您的类的构造函数中传递或作为您要测试的方法的参数传递。这将允许此类的使用者传递真实的 HttpContextWrapper ,然后在单元测试中可以模拟所需的方法。

You shouldn't use HttpContext.Current directly in your function as it is close to impossible to unit test, as you've already found out. I would suggest you using HttpContextBase instead, which is passed either in the constructor of your class or as an argument to the method you are testing. This will allow the consumers of this class to pass a real HttpContextWrapper and in your unit test you can mock the methods you need.

例如,下面是调用该方法的方法:

For example here's how you could call the method:

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

然后在您的单元测试中(使用犀牛Mo头():

And in your unit test (using Rhino Mocks):

var contextMock = MockRepository.GenerateMock<HttpContextBase>();
// TODO: Define expectations on the mocked object
Foo.UploadedFile(contextMock);

或者,如果愿意,可以使用构造函数注入

Or, if you prefer, use Constructor Injection.

这篇关于如何使HttpContext可供单元测试使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆