ŁukaszW.pl ŁukaszW.pl - 2 months ago 19
ASP.NET (C#) Question

How can I fake HttpContext for unit tests?

I need to fake

HttpContext.Current.Application
table in order to access it from my unit tests.

I need to store my data somewhere. I thought that I can just pass instance of
NameValueCollectionBase
but as I discovered this base type has no indexer so it seems too complicated to use.

So what about faking this part of
HttpContext
? Is it possible? How can I make it? Will be
NUnit.Mocks
helpful?

Thank you in advance...

Answer

If you need indexes for namevaluecollection base please use below code

public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection)
{
    if(collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key]));
}

For just to store data and passing around test methods please use above code.

Comments