如何设置索引属性的Moq

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

public class Index { IDictionary _backingField = new Dictionary(); 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.Setup(o => o["Key"]).Verifiable(); // act index.Object["Key"] = "Value"; //assert index.Verify(); } 

…失败了 – 它必须validationget{}

所以,我尝试使用SetupSet()

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

…它给出了运行时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) 

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

这应该工作

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

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