正如您正确发现的那样,有不同的方法可以分别初始化 getterSetupGet
和SetupSet
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 an indexed property and use the index value in the return/callback