1

I'm very new to testing and just starting out and want to know how could I make my AuthorizationService testable.

Reason is that I can't use Ninject to inject HttpContext.Current.Request into my AuthorizationService(IHttpContext context) since it has no interface.

How should I proceed?

Code

public class AuthorizationService : IAuthorizationService
{
    private readonly string _token;

    public AuthorizationService()
    {
        var headerValues = HttpContext.Current.Request.Headers.GetValues("Token");
        var paramValues = HttpContext.Current.Request.QueryString.GetValues("Token");
        var headerToken = string.Empty;
        var paramToken = string.Empty;

        // ... some logic ...

        this._token = headerToken;
    }

    /// <summary>
    /// Just some random function that will return the token
    /// </summary>
    /// <returns></returns>
    public string GetToken()
    {
        return this._token;
    }
}
Stan
  • 22,856
  • 45
  • 148
  • 231
  • that question has been asked a million times, just search for mocking httpcontext – Z. Danev May 07 '14 at 22:04
  • possible duplicate of [How do I mock the HttpContext in ASP.NET MVC using Moq?](http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp-net-mvc-using-moq) – Z. Danev May 07 '14 at 22:05

2 Answers2

1

Although HttpContext does not have an interfacce IHttpContext, it does have an abstract base class HttpContextBase which you can use for mocking.

MSDN documentation for HttpContextBase.

Personally I prefer separately injecting HttpRequestBase and HttpResponseBase so there is less to mock (dependant on your method of course).

dav_i
  • 25,285
  • 17
  • 94
  • 128
1

This is how you inject current context as contributor parameter.

kernel.Bind<IAuthorizationService>()
    .To<AuthorizationService>()
    .WithConstructorArgument("context", x => HttpContext.Current.Request);
Stan
  • 22,856
  • 45
  • 148
  • 231