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; }
}
}
some sample code to produce an error...
var mockSession = new HttpSessionMock();
var keys = mockSession.Keys;
Error: The method or operation is not implemented.
I need to implement the Keys property, but can't create a KeysCollection object.
What is the best way to do this?
EDIT: [SOLUTION]
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; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With