Unit test controller that uses application scoped variables

前端 未结 2 546
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 17:14

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.

I have a controll

2条回答
  •  悲哀的现实
    2021-01-25 17:56

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

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

    2. 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.

      private readonly IApplicationSettings _settings;

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

      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];
        }
    }
    

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

    var kernel = new StandardKernel();
    kernel.Bind().To();
    

提交回复
热议问题