1

I am unit testing some piece of code which behaves differently on different locales. I have created a fake HttpContext but need to set the locale for it and have not been able to. here is how i am creating fake HttpContext:

    public static HttpContext FakeHttpContext(string requestUrl)
    {
        var httpRequest = new HttpRequest("", requestUrl, "");
        var stringWriter = new StringWriter();
        var httpResponce = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponce);

        var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                new HttpStaticObjectsCollection(), 10, true,
                                                HttpCookieMode.AutoDetect,
                                                SessionStateMode.InProc, false);

        httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null, CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                            .Invoke(new object[] { sessionContainer });

        return httpContext;
    }
user3311522
  • 1,638
  • 3
  • 19
  • 33

3 Answers3

0

A while back I had to open up some services to better unit testing. I was able to achieve this using HttpContextBase and HttpContextWrapper. Have you looked at these at all? I seem to remember that they helped me a lot.

Here is at least on article talking about it. C# unit testing API 2 call

Community
  • 1
  • 1
Bomlin
  • 676
  • 4
  • 15
0

You don't need to mock the HttpContext. The culture can be changed using the Thread.CurrentThread.CurrentCulture properties:

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");

That is already discussed here: Set Culture in an ASP.Net MVC app

Community
  • 1
  • 1
Serhii Shushliapin
  • 2,528
  • 2
  • 15
  • 32
0

And finally solved:

    /// <summary>
    /// Fake HTTPCONTEXT generator
    /// </summary>
    /// <param name="extention">Http context extention</param>
    /// <param name="domain">Http context domain</param>
    /// <param name="locale">Http context locale</param>
    /// <returns>Fake Http Context</returns>
    private static HttpContext FakeHttpContext(string extention, string domain, string locale = "en-US,en;q=0.8")
    {
        HttpWorkerRequest httpWorkerRequest = new SimpleWorkerRequestHelper(false, domain, extention, locale);
        return new HttpContext(httpWorkerRequest);
    }

code for SimpleWorkerRequestHelper:

public class SimpleWorkerRequestHelper : SimpleWorkerRequest
{
    /// <summary>
    /// Whether the request is secure
    /// </summary>
    private string _domain;

    /// <summary>
    /// Whether the request is secure
    /// </summary>
    private string _locale;

    /// <summary>
    /// Initializes a new instance of the <see cref="SimpleWorkerRequestHelper" /> class.
    /// </summary>
    /// <param name="isSecure">Whether the helper request should be secure</param>
    public SimpleWorkerRequestHelper(bool isSecure, string domain = "", string extention = "/", string locale = "")
        : base(extention, AppDomain.CurrentDomain.BaseDirectory, string.Empty, string.Empty, new StringWriter())
    {
        _domain = domain;
        _locale = locale;
    }

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    public override String GetRemoteAddress()
    {
        if (string.IsNullOrEmpty(this._domain))
        {
            return base.GetRemoteAddress();
        }
        else
        {
            return this._domain;
        }
    }

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    public override String GetLocalAddress()
    {
        if (string.IsNullOrEmpty(this._domain))
        {
            return base.GetLocalAddress();
        }
        else
        {
            return this._domain;
        }
    }

    /// <summary>
    /// Overriding "GetKnownRequestHeader" in order to force "SimpleWorkerRequest" to return the fake value for locale needed for unit testing.
    /// </summary>
    /// <param name="index">Index associated with HeaderAcceptLanguage in lower level library</param>
    /// <returns>The language or the value from base dll</returns>
    public override string GetKnownRequestHeader(int index)
    {
        if (index == HttpWorkerRequest.HeaderAcceptLanguage && !string.IsNullOrEmpty(_locale))
        {
            return _locale;
        }
        else
        {
            return base.GetKnownRequestHeader(index);
        }
    }

}
user3311522
  • 1,638
  • 3
  • 19
  • 33