使用应用程序范围变量的单元测试控制器 [英] Unit test controller that uses application scoped variables

查看:25
本文介绍了使用应用程序范围变量的单元测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 ASP.NET MVC4 应用程序.我没有使用任何模拟框架,如果可能的话,此时不希望使用.我的问题是 2 部分.

I'm building an ASP.NET MVC4 app. I'm not using any mocking framework and, if possible, would prefer not to at this point. My question is 2 parts.

我有一个控制器,它使用在 Global.asax 中创建的变量.在控制器中,我像这样访问变量.

I have a controller that uses a variable created in Global.asax. In the controller I access the variable like this.

HttpContext.Application["MyVar"]

1) 这是应用广泛的变量使用的最佳实践吗?如果没有,最好的方法是什么?

1) Is this a best-practice for application wide variable usage? If not, what's the best way?

为了对该控制器进行单元测试,我添加了以下代码(来自 此处) 到我的测试方法.

In an attempt to unit test this controller I added the following code (from here) to my test method.

MyController target = new MyController();
var request = new HttpRequest("", "http://example.com/", "");
var response = new HttpResponse(System.IO.TextWriter.Null);
var httpContext = new HttpContextWrapper(new HttpContext(request, response));
target.ControllerContext = new ControllerContext(httpContext, new RouteData(), target);
target.ControllerContext.HttpContext.Application["MyVar"] = new MyVar();

问题是我无法向应用程序添加任何内容.最后一行代码似乎没有做任何事情,集合仍然是空的.我也在 VS 的 Immediate Window 中尝试过这个,但没有成功.

The problem is I can't add anything to Application. The last line of code doesn't seem to do anything and the collection remains empty. I've also tried this in VS's Immediate Window without success.

2) 在单元测试中,如何添加控制器需要的应用级变量?

2) In the unit test, how can I add the application level variables the controller needs?

推荐答案

通常全局变量不适合测试.您至少可以采用两种方法.

In general globals aren't good for testing. There are at least two approaches you could take.

  1. 使用模拟框架,例如 Pex/Moles、NMock等

使用控制反转方法(NInject 是我的最爱).如果像控制器这样的类具有外部依赖项,它会要求提供接口,通常在其构造函数中.

Use an inversion-of-control approach (NInject is my favorite). If class like a controller has an external dependency, it asks for the interface, typically in its constructor.

私有只读 IApplicationSettings _settings;

private readonly IApplicationSettings _settings;

public MyController(IApplicationSettings 设置){_settings = 设置;}

public MyController(IApplicationSettings settings) { _settings = settings; }

void someMethod(){_settings.Get("MyVar");}

void someMethod() { _settings.Get("MyVar"); }

通过这种方式,您可以编写真实的和测试的实现.

This way you can write real and test implementations.

public LiveAppSettings : IApplicationSettings
{
    public string Get(string key)
    { 
        return HttpContext.Current.Application[key];
    }
}

使用 Ninject,您可以在应用程序启动时绑定任一实现:

With Ninject, you can bind either implementation at application startup:

var kernel = new StandardKernel();
kernel.Bind<IApplicationSettings>().To<LiveAppSettings>();

这篇关于使用应用程序范围变量的单元测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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