如何伪造HttpContext进行单元测试?

Łuk*_*.pl 9 c# asp.net nunit unit-testing httpcontext

我需要假HttpContext.Current.Application表来从我的单元测试中访问它.

我需要将我的数据存储在某个地方.我以为我可以传递实例NameValueCollectionBase但是因为我发现这个基类型没有索引器所以它看起来太复杂了.

那假装这部分HttpContext怎么样?可能吗?我该怎么做?会有NUnit.Mocks帮助吗?

先感谢您...

Ven*_*kat 1

如果您需要名称值集合基础的索引,请使用以下代码

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]));
}
Run Code Online (Sandbox Code Playgroud)

仅用于存储数据和传递测试方法,请使用上面的代码。