简体   繁体   English

如何设置索引属性的Moq

[英]How to Moq Setting an Indexed property

I'm trying to use mock to verify that an index property has been set. 我正在尝试使用mock来验证是否已设置索引属性。 Here's a moq-able object with an index: 这是一个带有索引的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; }
    }
}

First, tried using Setup() : 首先,尝试使用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{} ...失败了 - 必须验证get{}

So, I tried using SetupSet() : 所以,我尝试使用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? 完成此任务的正确方法是什么?

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. 您可以像对待普通的属性设置器一样对待它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM