Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
    }
}

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.

like image 808
joelnet Avatar asked Aug 09 '11 00:08

joelnet


1 Answers

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; }
    }
}
like image 97
scdove Avatar answered Nov 02 '22 17:11

scdove