Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Moq Setting an Indexed property

Tags:

c#

moq

I'm trying to use mock to verify that an index property has been set. Here's a moq-able object with an index:

public class Index
{
    IDictionary<object ,object> _backingField 
        = new Dictionary<object, object>();

    public virtual object this[object key]
    {
        get { return _backingField[key]; }
        set { _backingField[key] = value; }
    }
}

First, tried using Setup():

[Test]
public void MoqUsingSetup()
{
    //arrange
    var index = new Mock<Index>();
    index.Setup(o => o["Key"]).Verifiable();
    // act
    index.Object["Key"] = "Value";
    //assert
    index.Verify();
}

...which fails - it must be verifying against get{}

So, I tried using SetupSet():

[Test]
public void MoqUsingSetupSet()
{
    //arrange
    var index = new Mock<Index>();
    index.SetupSet(o => o["Key"]).Verifiable();
}

... which gives a runtime exception:

System.ArgumentException : Expression is not a property access: o => o["Key"]
at Moq.ExpressionExtensions.ToPropertyInfo(LambdaExpression expression)
at Moq.Mock.SetupSet(Mock mock, Expression`1 expression)
at Moq.MockExtensions.SetupSet(Mock`1 mock, Expression`1 expression)

What's the correct way to accomplish this?

like image 564
James Kolpack Avatar asked Mar 03 '10 16:03

James Kolpack


1 Answers

This should work

[Test]
public void MoqUsingSetup()
{
    //arrange
    var index = new Mock();
    index.SetupSet(o => o["Key"] = "Value").Verifiable();
    // act
    index.Object["Key"] = "Value";
    //assert
    index.Verify();
}

You can just treat it like a normal property setter.

like image 91
Shane Fulmer Avatar answered Sep 23 '22 05:09

Shane Fulmer