As you rightly noted, there are various SetupGet and SetupSet for initializing getters and setters, respectively. Although SetupGet intended to be used for properties, not for indexers, it will not allow you to process the key passed to it. To be precise, for indexers, SetupGet will call Setup anyway:
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); ... } ... }
To answer your question, here is a sample code using a basic Dictionary to store values:
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 vaue) => dictionary[key] = vaue);
As you can see, you need to explicitly specify the key to configure the indexer installer. Details are described in another SO question: Moq indexed property and use index value in callback / callback
Vitaliy Ulantikov Jun 03 '16 at 8:44 2016-06-03 08:44
source share