如何设置索引属性的Moq

时间:2010-03-03 16:18:40

标签: c# moq

我正在尝试使用mock来验证是否已设置索引属性。这是一个带有索引的moq-able对象:

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

首先,尝试使用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();
}

...失败 - 必须针对get{}

进行验证

所以,我尝试使用SetupSet()

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

...它给出了运行时异常:

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)

实现这一目标的正确方法是什么?

1 个答案:

答案 0 :(得分:8)

这应该有效

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

您可以像对待普通的属性设置器一样对待它。