我正在尝试使用模拟来验证是否已设置索引属性。这是一个带有索引的可定量对象:

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)

什么是实现此目的的正确方法?

最佳答案

这应该工作

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

您可以将其视为普通的属性 setter 。

关于c# - 如何起订索引属性的最小起订量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2372938/

10-10 22:26