Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to MOQ an Indexed property

Tags:

c#

tdd

mocking

moq

I am attempting to mock a call to an indexed property. I.e. I would like to moq the following:

object result = myDictionaryCollection["SomeKeyValue"];

and also the setter value

myDictionaryCollection["SomeKeyValue"] = myNewValue;

I am doing this because I need to mock the functionality of a class my app uses.

Does anyone know how to do this with MOQ? I've tried variations on the following:

Dictionary<string, object> MyContainer = new Dictionary<string, object>();
mock.ExpectGet<object>( p => p[It.IsAny<string>()]).Returns(MyContainer[(string s)]);

But that doesn't compile.

Is what I am trying to achieve possible with MOQ, does anyone have any examples of how I can do this?

like image 528
Ash Avatar asked Dec 04 '08 14:12

Ash


2 Answers

It's not clear what you're trying to do because you don't show the declaration of the mock. Are you trying to mock a dictionary?

MyContainer[(string s)] isn't valid C#.

This compiles:

var mock = new Mock<IDictionary>();
mock.SetupGet( p => p[It.IsAny<string>()]).Returns("foo");
like image 158
Mike Scott Avatar answered Nov 15 '22 09:11

Mike Scott


Ash, if you want to have HTTP Session mock, then this piece of code does the job:

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

/// <summary>
/// Base class for all controller tests.
/// </summary>
public class ControllerTestSuiteBase : TestSuiteBase
{
    private readonly HttpSessionMock sessionMock = new HttpSessionMock();

    protected readonly Mock<HttpContextBase> Context = new Mock<HttpContextBase>();
    protected readonly Mock<HttpSessionStateBase> Session = new Mock<HttpSessionStateBase>();

    public ControllerTestSuiteBase()
        : base()
    {
        Context.Expect(ctx => ctx.Session).Returns(sessionMock);
    }
}
like image 20
wasker Avatar answered Nov 15 '22 07:11

wasker