如何设置索引属性的Moq

Jam*_*ack 9 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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

首先,尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)

......失败了 - 它一定要经过验证 get{}

所以,我尝试使用SetupSet():

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

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

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)
Run Code Online (Sandbox Code Playgroud)

完成此任务的正确方法是什么?

Sha*_*mer 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();
}
Run Code Online (Sandbox Code Playgroud)

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

  • 如果它迎合了没有索引属性设置器的模拟类(就像我的情况一样),这将是一个更好的答案(不是鄙视它) (2认同)