正如您正确发现的那样,有不同的方法SetupGet
以及SetupSet
分别初始化getter和setter的方法。尽管SetupGet
旨在用于属性,但不能用于索引器,并且不允许您处理传递给它的键。确切地说,对于索引器,无论如何SetupGet
都会调用Setup
:
internal static MethodCallReturn<T, TProperty> SetupGet<T, TProperty>(Mock<T> mock, Expression<Func<T, TProperty>> expression, Condition condition) where T : class
{
return PexProtector.Invoke<MethodCallReturn<T, TProperty>>((Func<MethodCallReturn<T, TProperty>>) (() =>
{
if (ExpressionExtensions.IsPropertyIndexer((LambdaExpression) expression))
return Mock.Setup<T, TProperty>(mock, expression, condition);
...
}
...
}
为了回答您的问题,这是一个使用基础Dictionary
存储值的代码示例:
var dictionary = new Dictionary<string, object>();
var applicationSettingsBaseMock = new Mock<SettingsBase>();
applicationSettingsBaseMock
.Setup(sb => sb[It.IsAny<string>()])
.Returns((string key) => dictionary[key]);
applicationSettingsBaseMock
.SetupSet(sb => sb["Expected Key"] = It.IsAny<object>())
.Callback((string key, object value) => dictionary[key] = value);
如您所见,您必须显式指定键以设置索引器二传手。详细信息在另一个SO问题中进行了描述:Moq一个索引属性,并在返回/回调中使用索引值