如何设置最小起订量索引属性 [英] How to Moq Setting an Indexed property

查看:209
本文介绍了如何设置最小起订量索引属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用模拟来验证索引属性被设置。下面是带索引的起订量,能够对象:

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



首先,使用试过设置()

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



...这失败 - 它必须验证对获得{}

所以,我尝试使用 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?

推荐答案

这应该工作

[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。

You can just treat it like a normal property setter.

这篇关于如何设置最小起订量索引属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆