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

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

问题描述

我要建一个ASP.NET应用程序MVC4。我没有使用任何嘲弄的框架,如果可能的话,将preFER不要在这一点上。我的问题是两部分。

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?

在试图单元测试此控制器添加以下code(从的这里),以我的测试方法。

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();

问题是我无法应用添加任何东西。 code的最后一行似乎并没有做任何事情,集合保持空。我也试过这个在VS的立即窗口没有成功。

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 /鼹鼠,NMock嘲弄框架等等。

  1. Use a mocking framework like Pex/Moles, NMock, etc.

使用反转的控制办法( 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;

公共myController的(IApplicationSettings设置)
{
    _settings =设置;
}

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

无效的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天全站免登陆