我怎样才能正确地莫克在HttpSessionStateBase的KeysCollection? [英] How can I properly Mock the KeysCollection in HttpSessionStateBase?
问题描述
我安装在这里的例子此模拟会话对象:如何起订量索引属性
I setup this mock session object from the example here: How to MOQ an Indexed property
/// <summary>
/// HTTP session mockup.
/// </summary>
internal sealed class HttpSessionMock : HttpSessionStateBase
{
private readonly Dictionary<string, object> objects = new Dictionary<string, object>();
public override object this[string name]
{
get { return (objects.ContainsKey(name)) ? objects[name] : null; }
set { objects[name] = value; }
}
}
一些示例code,以产生一个错误...
some sample code to produce an error...
var mockSession = new HttpSessionMock();
var keys = mockSession.Keys;
错误:的方法或操作不落实
我需要实现键的属性,但不能创建一个KeysCollection对象。
I need to implement the Keys property, but can't create a KeysCollection object.
什么是做到这一点的最好方法是什么?
What is the best way to do this?
编辑:[解决]
我最终改变的基础上给出的答案HttpSessionMock。这是我结束了。 (我也加入到System.Linq的参照点);
I ended up changing the HttpSessionMock based on the answer given. This is what I ended up with. (I also added a reference to System.Linq).
internal sealed class HttpSessionMock : HttpSessionStateBase
{
private readonly NameValueCollection objects = new NameValueCollection();
public override object this[string name]
{
get { return (objects.AllKeys.Contains(name)) ? objects[name] : null; }
set { objects[name] = (string)value; }
}
public override NameObjectCollectionBase.KeysCollection Keys
{
get { return objects.Keys; }
}
}
请注意:此模拟会议将只存储字符串,而不是对象
note: this mock session will only store strings, not objects.
推荐答案
我发现原来的做法和接受的解决方案的结合,使对象的存储和执行键的属性:
I found a combination of the original approach and the accepted solution allows both storing of objects and implementing the keys property:
public class HttpSessionMock : HttpSessionStateBase
{
private readonly NameValueCollection keyCollection = new NameValueCollection();
private readonly Dictionary<string, object> objects = new Dictionary<string, object>();
public override object this[string name]
{
get
{
object result = null;
if (objects.ContainsKey(name))
{
result = objects[name];
}
return result;
}
set
{
objects[name] = value;
keyCollection[name] = null;
}
}
public override NameObjectCollectionBase.KeysCollection Keys
{
get { return keyCollection.Keys; }
}
}
这篇关于我怎样才能正确地莫克在HttpSessionStateBase的KeysCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!